API Dummy

API dummy can be implemented in various ways, depending on the specific requirements of the project.

Overview

API dummy is a mock implementation of the API that can be used for testing and development purposes. An API dummy can be used to simulate the expected behavior of the actual API, allowing the front-end developers to test and develop their code without relying on the back-end team.

How to use

Here we use API Dummy. The installation method is as follows below.

Step 1: Create a mock data file

Create a db.json file with some mock data:

pages/api/db.json
{
  "posts": [
    {
      "id": 1,
      "title": "Post 1",
      "body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
    },
    {
      "id": 2,
      "title": "Post 2",
      "body": "Sed ut perspiciatis unde omnis iste natus error sit voluptatem."
    },
    {
      "id": 3,
      "title": "Post 3",
      "body": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia."
    }
  ]
}

Step 2: Create an API route

Create an API route that serves the mock data using json-server:

pages/api/posts.ts
import { createServer } from 'json-server';
import { NextApiRequest, NextApiResponse } from 'next';
import path from 'path';

const server = createServer();
const router = server.router(path.join(process.cwd(), 'src/pages/api/db.json'));

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  await router(req, res);
}

In this example, we're creating a json-server instance and configuring it to use the db.json file as the data source. We then export a default async function that passes the request and response objects to the json-server router.

Step 3: Test the API route

Start your Next.js development server:

yarn dev

Visit http://localhost:3000/api/posts in your browser to see the mock data served by the API route.

Last updated