Mock multiple APIs in React using json-server in less than 3 mins!
- Install json-server globally using the below command.
npm install -g json-server
2. Add the following under the “scripts” section in the “package.json” file.
“server”: “json-server — watch ./src/mocks/index.js — port 8000”
3. Create index.js under src/mocks (or any location) and type the following:
const books = require('./books.json');
const cities = require('./cities.json');
module.exports = () => ({
books: books,
cities: cities,
});
4. Create books.json under src/mocks and add json data here:
{“data”: [{
“name”:”Paraworld Zero”
}, {
“name”:”Revolution 2020”
} ]}
5. Create cities.json under src/mocks and add json data here:
{“data”: [{
“name”:”Chennai”
}, {
“name”:”Kolkata”
} ]}
6. Run the server using following command:
npm run server
7. Check out the APIs that we mocked using json-server at:
http://localhost:8000/cities
http://localhost:8000/books