Open PortfolioOpen Portfolio.
โ† Back to Blog

The Developer's Guide to API Mocking

June 16, 2026at 2:01 PM UTCBy Pocket Portfolio TeamTechnology
The Developer's Guide to API Mocking
#api#developer#mocking#guide

Problem

Developers often face challenges when working with APIs that are still in development or when services are unreliable. This can lead to delays and increased testing complexity. Mocking APIs allows developers to simulate API behavior, enabling them to continue development and testing independently of the actual API availability.

Solution

API mocking provides a way to create a fake version of the API that mimics the expected behavior and responses. This can be implemented easily using various libraries and tools. Here, we will demonstrate how to use json-server, a popular tool for mocking REST APIs.

Step-by-Step Implementation

  1. Install json-server

    First, ensure you have Node.js installed. Then, you can install json-server using npm:

    npm install -g json-server
    
  2. Create a Mock Data File

    Create a db.json file in your project's root directory. This file will contain the mock data you want your API to return. Example structure:

    {
      "posts": [
        { "id": 1, "title": "Mocking APIs", "author": "John Doe" },
        { "id": 2, "title": "Understanding JSON Server", "author": "Jane Smith" }
      ],
      "comments": [
        { "id": 1, "postId": 1, "body": "Great article!" }
      ]
    }
    
  3. Start the Mock Server

    Run the following command to start the server:

    json-server --watch db.json
    

    By default, this will start a server at http://localhost:3000. You can now make HTTP requests to this server, and it will respond with the data from your db.json.

  4. Integrate with Your Application

    In your application, replace actual API endpoints with the mocked endpoints. This allows you to test your application without depending on the real API.

    fetch('http://localhost:3000/posts')
      .then((response) => response.json())
      .then((data) => console.log(data));
    

Key Concepts

  • Mock Data: Fake data returned by the mocked API, allowing for consistent testing scenarios.
  • Endpoint Simulation: Using tools like json-server to create endpoints that mimic the expected behavior of real APIs.
  • Decoupling: Reducing dependencies on external services by using mocks, thereby enabling continuous development and testing.

API mocking is a critical practice in modern software development, improving efficiency and reliability. By incorporating tools like json-server, developers can simulate APIs, streamline workflows, and minimize disruptions caused by third-party service downtime or ongoing API development.

The Developer's Guide to API Mocking | Open Portfolio Blog | Open Portfolio