What is a mock API? How to create a mock API server with Postman

The term "mock API" comes up often in application development. So what is a mock API, and how do you create one?

What is a mock API?

A mock API is a technique for creating simulated data that reproduces the behavior of a real API, for testing, development or other purposes, without having to call a real API or wait until a real API is deployed.
 

What is a mock API? How to create a mock API server with Postman - Image 1.

Mock APIs in software development

Mock APIs are used extensively in software development because they let developers run tests without connecting to the real service, which limits security risk and delay.

Minimize delay:Using mock APIs for interaction testing reduces delays during software development.

Reducing security-related risk:With a mock API, developers can run tests without connecting to live services, which reduces the security exposure involved.

Large library of ready-made Mock APIs:The range of mock API libraries and services is large and ready to use. For example, connect-api-mocker or Castle Mock can be used to create fake APIs.

Popular tools for creating a mock API

A mock API is a simulated API for a website, and to create one, developers can use any of the following tools:

MockAPI: Creating a mock API with this tool is straightforward: you simply create the simulated endpoints and add the data to be returned. MockAPI also gives users access control, data encryption and API management features.

Postman:This is a capable tool for creating and managing mock APIs: users can create mock APIs for an endpoint and check how they behave.

Swagger: An effective API and mock API platform: create simulated endpoints easily and test them yourself in the browser.

WireMock:Among the tools for building mock APIs, this is the most popular and most widely used. It lets you simulate an endpoint in a range of states and then inspect the API's requests and responses.

Create a mock API server with Postman

Creating a mock API server in Postman is not difficult; just follow the Bizfly Cloud guide below:

Step 1:Create a new API collection

What is a mock API? How to create a mock API server with Postman - Image 2.

Step 2:In the API collection you just created, create a new request and select Mock mode

What is a mock API? How to create a mock API server with Postman - Image 3.

Step 3:Select “Create a mock server” to configure the mock server's settings, name, description and the OpenAPI object to register.

What is a mock API? How to create a mock API server with Postman - Image 4.

Step 4: Copy URL Mock server

What is a mock API? How to create a mock API server with Postman - Image 5.

Step 5:Update the configuration with the new URL to simulate a real server

What is a mock API? How to create a mock API server with Postman - Image 6.

Step 6:Add mock response templates by importing service definition files (WSDL, WADL, Swagger) or by manually loading JSON, XML or CSV files to test the mock API

Step 7:Send a request to test the mock APIs.

Dynamic routes in Mock API

Dynamic routes in a Mock API are a technique for creating different API endpoints from a single template. For example, rather than creating multiple endpoints to fetch a user's details, create one /users/:id route and pass in the ID parameter.

How to use dynamic routes in Mock API

To create mock APIs, you need to configure mock endpoints that correspond to the dynamic routes, and to pass parameters in the request when testing the API.

Example:

Use json-server-router to define a /users/:id endpoint as follows:

“`

const jsonServer = require(\’json-server\’);

const router = jsonServer.router(\’db.json\’);

const bodyParser = require(\’body-parser\’);

const _ = require(\’lodash\’);

function findById(db, id) {

return _.find(db.users, { id: parseInt(id) });

}

router.render = (req, res) => {

const db = res.locals.db;

const data = res.locals.data;

if (req.method === \’GET\’ && req.params.id) {

const user = findById(db, req.params.id);

res.jsonp(user);

} else {

res.jsonp(data);

}

};

router.db._.id = \’id\’;

const server = jsonServer.create();

server.use(bodyParser.json());

server.use(\’/api\’, router);

server.listen(3000);

“`

In the code above, the findById function looks up a user by ID in the database, and the render function returns the details of the user with that ID. Next, create the dynamic route /users/:id and register it on the server's /api endpoint.

To fetch a single user by ID, call the route http://localhost:3000/api/users/1; to fetch all users, call the route http://localhost:3000/api/users.

Unit testing with AspectMock and Mock API

AspectMock and its role in unit testing

AspectMock is an optimized PHP mocking framework that lets you use conventional methods to mock objects that otherwise cannot be mocked.

How to use AspectMock for unit testing

Step 1: Install AspectMock

Add the following lines to the `composer.json` file

“`json

{

\”require-dev\”: {

\”codeception/aspect-mock\”: \”*\”

}

}

“`

Run the `composer update` command

Step 2: Create a test case

Example:

“`php

use AspectMock\\Test as test;

class MyTest extends \\PHPUnit\\Framework\\TestCase

{

public function testSomething()

{

$object = new MyObject();

$mock = test::double($object, [\’getName\’ => \’mockedName\’]);

$this->assertEquals(\’mockedName\’, $object->getName());

}

}

“`

In the code above the object is `MyObject` and the mocked method is `getName()`, so AspectMock will return the value `mockedName`.

Step 3: Run the test

Run `phpunit` so AspectMock applies the mocks and returns the stubbed values where defined.

Similar Posts