Understanding Mock API in JavaScript: A Beginner's Guide

Discover the power of mock APIs in JavaScript! Learn how to create, manage, and test mock APIs effortlessly with Apidog. Speed up your development, improve testing, and collaborate better.

Ashley Innocent

Ashley Innocent

7 May 2025

Understanding Mock API in JavaScript: A Beginner's Guide

Hey there, fellow developers! Have you ever found yourself in the middle of building an amazing web application, only to hit a wall because you’re waiting on an API to be ready? Frustrating, right? Well, that’s where mock APIs come to the rescue, especially when you’re working with JavaScript. And guess what? Tools like Apidog make this process even more seamless.

💡
Download Apidog for free to effortlessly create, manage, and test your mock APIs, and keep your development workflow smooth and uninterrupted.
button

So, let’s dive into the world of mock APIs in JavaScript and explore how they can boost your development process!

What is a Mock API?

A mock API simulates the behavior of a real API by providing predefined responses to specific requests. It’s like a stand-in for the actual API, allowing developers to continue building and testing their applications without having to wait for the backend services to be completed.

Why Use Mock APIs?

Mock APIs are incredibly useful for several reasons:

  1. Speed Up Development: No more waiting for backend developers. Start integrating APIs as soon as you begin coding your frontend.
  2. Testing: They help in thoroughly testing your application by providing consistent responses.
  3. Isolation: You can isolate your frontend development from the backend, reducing dependencies.
  4. Collaboration: Teams can work in parallel without blocking each other.

Getting Started with Mock APIs in JavaScript

Now, let’s get hands-on. Here’s how you can set up a mock API in JavaScript.

Step 1: Setting Up Your Project

First, create a new JavaScript project. If you’re using Node.js, you can start with:

mkdir mock-api-demo
cd mock-api-demo
npm init -y

Install Express.js, a popular web framework for Node.js:

npm install express

Step 2: Creating Your Mock API

Create a file named server.js in your project directory. This file will contain the code for your mock API.

const express = require('express');
const app = express();
const port = 3000;

app.use(express.json());

app.get('/api/users', (req, res) => {
    res.json([
        { id: 1, name: 'John Doe' },
        { id: 2, name: 'Jane Smith' }
    ]);
});

app.listen(port, () => {
    console.log(`Mock API server running at http://localhost:${port}`);
});

Run the server with:

node server.js

You now have a mock API running at http://localhost:3000/api/users that returns a list of users.

Introducing Apidog

While writing your own mock APIs is great, tools like Apidog make it even easier and more powerful. Apidog is a comprehensive tool that helps you create, manage, and test APIs effortlessly.

button

Why Choose Apidog?

  1. User-Friendly Interface: No need to write code from scratch. Apidog provides a visual interface to define your APIs.
  2. Collaboration: Share your API definitions with your team easily.
  3. Testing: Built-in tools to test your APIs right from the interface.
  4. Documentation: Automatically generate API documentation.

Step 1. Create a New Project

Apidog uses projects to manage APIs. You can create multiple APIs under one project. Each API must belong to a project. To create a new project, click the "New Project" button on the right side of the Apidog app homepage.

Create a New Project

Step 2. Create a New API

To demonstrate the creation of an API for user details, follow these steps:

{
id: number, // user id
name: string, // username
gender: 1 | 2, // gender: 1 for male, 2 for female
phone: string, // phone number
avatar: string, // avatar image address
}

To create a new interface, go to the homepage of the previously created project and click on the "+" button on the left side.

Create a New Interface

Fill in the corresponding interface information and save it.

Parameters
Responese

With this, the user detail interface has been created. Meanwhile, Apidog has automatically generated a mock for us based on the format and type of the response fields. Click on the " Request" button under Mock to view the mock response.

API Request

Let's take a look at the mock response. Click on the "Request" button and then click "Send" on the page that opens.

img
Send the Request

Step 3. Set Mock  Matching Rules

Have you noticed something magical? Apidog set the "name" field to string type, yet it returns names; set the "phone" field to string type, yet it returns phone numbers; set the "avatar" field to string type, yet it returns image addresses.

The reason is that Apidog supports setting matching rules for Mock. Apidog has built-in rules, and users can also customize their own rules. These rules can be found in Project Settings > Feature Settings > Mock Settings.

 Set Mock  Matching Rules

You can also set dedicated Mock rules for each field. Click on the "Mock" next to the field:

Mock

Apidog Mock matching rules are as follows:

  1. When a field meets a matching rule, the response will return a random value that satisfies the Mock rule.
  2. If a field does not meet any matching rule, the response will return a random value that meets the data type of the field.

There are three types of matching rules:

  1. Wildcards: * matches zero or more characters, and ? matches any single character. For example, *name can match user name, name, and so on.
  2. Regular expressions.
  3. Exact match.

Mock rules are fully compatible with Mock.js, and have extended some syntax that Mock.js does not have (such as domestic phone numbers "@phone"). Commonly used Mock rules include:

  1. @integer: integer. @integer(min, max).
  2. @string: string. @string(length): specifies the length of the string.
  3. @regexp(regexp): regular expression.
  4. @url: URL.

During development, we may encounter flexible and complex Mock scenarios, such as returning customized content based on different request parameters. For example, return normal user information when the ID is 1, and report an error when the ID is 2. Apidog also supports these scenarios, and those interested can check out the Advanced Mock document.

Advanced Mock API Techniques

Dynamic Responses

Sometimes, static responses aren’t enough. You might need your mock API to return different data based on the request. Let’s enhance our previous example.

app.get('/api/users/:id', (req, res) => {
    const users = [
        { id: 1, name: 'John Doe' },
        { id: 2, name: 'Jane Smith' }
    ];

    const user = users.find(u => u.id == req.params.id);
    if (user) {
        res.json(user);
    } else {
        res.status(404).send('User not found');
    }
});

Now, you can request a specific user by their ID, and the mock API will return the corresponding user or a 404 error if the user is not found.

Delay Responses

To simulate network latency, you can introduce delays in your responses. This can be useful for testing how your application handles slow networks.

app.get('/api/users', (req, res) => {
    setTimeout(() => {
        res.json([
            { id: 1, name: 'John Doe' },
            { id: 2, name: 'Jane Smith' }
        ]);
    }, 2000); // 2 seconds delay
});

How to Generate User-Friendly Mock Data Efficiently with Apidog?

Below is an example of mock data generated by Apidog without any configuration:

adada

Best Practices for Using Mock APIs

  1. Keep It Simple: Start with simple, static responses and gradually add complexity as needed.
  2. Document Your Mock APIs: Ensure your team knows the available endpoints and their responses.
  3. Regular Updates: Keep your mock APIs updated as the real APIs evolve.
  4. Test Thoroughly: Use the mock APIs to test different scenarios, including edge cases.

Real-World Use Cases

Frontend Development

When building a frontend application, you can use mock APIs to start working on features immediately, without waiting for the backend to be ready. This approach helps in parallel development and speeds up the overall process.

Automated Testing

Mock APIs are essential for automated testing. They provide consistent responses, making it easier to write reliable tests. Tools like Jest and Cypress can integrate with mock APIs to test various components and flows.

Prototyping

When creating prototypes or proofs of concept, mock APIs enable you to quickly set up the necessary backend interactions without investing time in building the actual backend services.

Conclusion

Mock APIs are a game-changer for developers, providing a way to speed up development, improve testing, and facilitate better collaboration. With tools like Apidog, creating and managing mock APIs becomes a breeze, allowing you to focus on building amazing applications.

So, the next time you find yourself waiting on an API, remember that mock APIs are your best friend. And don’t forget to check out Apidog for a hassle-free experience!

Call to Action: Ready to supercharge your development process? Download Apidog for free and start creating your mock APIs today!

Explore more

A Developer's Guide: How to Generate API Specifications with Vercel v0 Workflows

A Developer's Guide: How to Generate API Specifications with Vercel v0 Workflows

In the fast-paced world of web development, efficiency and clarity are paramount. As projects grow in complexity, so does the need for well-defined APIs. A clear API specification acts as a contract between the frontend and backend, ensuring seamless communication and a smoother development process. But creating these specifications can be a tedious and time-consuming task. Enter Vercel's v0, an AI-powered tool designed to streamline the development workflow. While v0 is known for its ability t

7 June 2025

Kong Pricing 2025 Explained, and 8 Kong Alternatives to Consider

Kong Pricing 2025 Explained, and 8 Kong Alternatives to Consider

The role of an API gateway is paramount. It acts as the central nervous system for managing, securing, and scaling API traffic. Kong, a dominant player in this space, offers a powerful and flexible solution. However, understanding its pricing structure and how it stacks up against the competition is crucial for any organization looking to make an informed decision. This comprehensive article delves into the intricacies of Kong's pricing and explores the top eight alternatives, offering a detaile

7 June 2025

How to Extract Data from APIs for Data Pipelines using Python

How to Extract Data from APIs for Data Pipelines using Python

Application Programming Interfaces (APIs) have emerged as the linchpins of modern data architecture. They are the conduits through which applications communicate and exchange information, making them an invaluable resource for building robust and dynamic data pipelines. The ability to effectively extract data from APIs using a versatile language like Python is a cornerstone skill for any data engineer, data scientist, or analyst. This article will delve into the intricacies of this process, prov

7 June 2025

Practice API Design-first in Apidog

Discover an easier way to build and use APIs