What is a Mock API?
With APIs, to mock is to copy or imitate. Mock APIs provide predefined API responses for client applications. For example, think of an application that has a database. We may want to create a mock API for that database that returns example data representations. Therefore, we can take a handful of common data objects from the database and place them into a mock API.
Developers and client applications can interact with mock APIs the same way they interact with real APIs. However, “mocks” do not provide authentic interactions. This is a common drawback of using mocks APIs. Before we discuss the disadvantages, let me explain the advantages of mock APIs.
Why Mock API Data?
Development teams want to design, develop, and ship code efficiently. Unfortunately, one major impediment to developing efficiently is setting up a backend for developers to test and run code with. Additionally, there might be more than one complicated back-end database in large applications that takes a week or more to set up.
A solution that gets developers coding as soon as possible is to create a mock API that returns example data.
Similarly, mock APIs can augment third-party API services. For example, if your application uses a third-party API, it may be expensive, wasteful, or impossible to call the API thousands of times during development or testing. In this scenario, it’s beneficial to create a mock of the data.
Disadvantages of Mock APIs
First, I already mentioned that mock APIs lack authentic data interactions. In an application, similar pieces of data may go through 4-5 transformations or processes in single user interactions. It’s less than reassuring for a developer that the data is “hypothetically” fetched or added through the API.
Second, mock APIs are another tool that requires maintenance. The accuracy of the example responses and server interactions are critical to the effectiveness of the mock API. The responsibility to update old request and response data fall on the developers, designers, or someone else on the team. As Alex Liu of Confluent observed1, “Once updated, the mock server would again start accumulating dust until the next cleaning was required.” If the mock API is outside of the everyday development workflow, it could become obsolete.
So far, I haven’t made a distinction between the different types of mock APIs. In the next section, I’ll explain a couple of kinds of mocks and their implementation characteristics.
Where to Mock?
Local Mock API Server
Mock API servers are implemented locally or externally. Local mock servers are often part of the code repository. They are built and maintained with tools2 like:
A similar option is the tool Interceptor that works as a browser extension.
Due to the technical knowledge required and proximity to the code base, local mock API servers are maintained by developers. A few benefits of local mocks are flexibility, security, and availability.
Public Mock API
Alternatively, mock APIs are accessed over the network and are separate from the development or staging environment. Therefore, an active internet connection is necessary for reaching the API with client requests. External mocks are popular because a team can automatically generate a mock API from an API design specification.
Consequently, many services exist that allow users to quickly create mock APIs, documentation, and software development kits (SDKs) all in one place.
Automatically Generating Mock APIs
First, I need to introduce the OpenAPI Specification so you can understand how services automatically generate mock APIs. OAS (the OpenAPI Specification) was formerly known as the Swagger Spec. The specification follows a format that can describe an API’s:
- basic information
- servers
- routes
- responses
- data models
- headers
The format for OAS follows a simple syntax. Also worth noting is the implementation of the API described in the spec should be irrelevant to the data contained in the specification. This makes specifications portable and reusable.
A sample from a popular OpenAPI specification looks like the data below:
Pet: type: object required: - name - photoUrls properties: id: type: integer format: int64 category: "$ref": "#/definitions/Category" name: type: string example: doggie photoUrls: type: array xml: name: photoUrl wrapped: true items: type: string tags: type: array xml: name: tag wrapped: true items: "$ref": "#/definitions/Tag" status: type: string description: pet status in the store enum: - available - pending - sold xml: name: Pet
It can look intimidating to someone new to OAS, but I’ll pull a relevant part in the next section.
An entire specification could generate a mock API, making it immediately accessible to client applications without additional configuration or code. It may only require uploading the specification to an online service provider. Later, we’ll see this option available when we create a mock API on RapidAPI. Next, you may be asking, what does a mock API response look like? In the next section, I’ll discuss how to represent example data in an OpenAPI specification file.
Mock API Responses
Toward the middle of the object in the previous section, we find the name
property. It has an attribute relevant to mocking: example
.
name: type: string example: doggie
Some services can recognize the examples in a specification and provide them as mock API responses. In OAS, there are a couple of ways to specify examples.
You can provide parameter examples or object examples. A parameter example is what was done for the name
parameter. An object example defines multiple parameters in one block.
The example given on Swagger’s documentation page is for a series of example User objects.
paths: /users: post: summary: Adds a new user requestBody: content: application/json: # Media type schema: # Request body contents $ref: '#/components/schemas/User' # Reference to an object examples: # Child of media type Jessica: # Example 1 value: id: 10 name: Jessica Smith Ron: # Example 2 value: id: 11 name: Ron Stewart responses: '200': description: OK
Values for the referenced User object ($ref) are hardcoded into the spec. Although this is useful, some online tools or mocking services allow the user to be more explicit about the response they wish to mock.
Creating an OpenAPI spec from scratch can be tedious and unattractive. Consequently, services try to augment the plain experience with user interfaces that are friendly to use. In the next section, I’ll demonstrate how this is done with RapidAPI.
How to Create a Mock API
In this walkthrough, I’ll demonstrate how we can set up a mock response in RapidAPI that could help our team “..get a head start on API integration.”
Add a New API to RapidAPI
Please navigate to the provider dashboard by clicking on My APIs after you sign in (or sign up) on RapidAPI.
On the dashboard, select the Add New API menu item on the left sidebar.
Then, add the following data for the API:
- API Name – Mocking Example
- Short Description – Example mock API.
- Category – Other
Select UI for the Specify using option.
Click Add API.
Create New Endpoint
After redirecting to the API dashboard, click on the API Spec tab and select Endpoints.
On the Endpoints tab, click Create REST Endpoint.
In the endpoint form, add the following information:
- Name – Mock
- Description – Example user data
- Endpoint – /mock/data
Add Mock Response
To add a mock response, we first must create an example response.
Scroll down the Responses section.
Add a new example response with a status code of 200.
After the new Example Response form appears, add the following object to the Body input for the response.
{ "id": 1, "name":"Jarrett" }
Then, click the Schema tab next to the Body tab and insert this object:
{ "type": "object", "properties": { "id": { "type": "integer" }, "name": { "type": "string" } } }
Click the Mock Response option on the Response section bar.
Enter 200 for the status code.
After that, insert the example object.
{ "id": 1, "name":"Jarrett" }
Finally, toggle Enable Mock Response to ON.
Click Save in the bottom right.
Test Mock API
Back on your API’s dashboard, click View in Marketplace. The API is still private, but we can see what it will look like and even interact with it before publishing.
If you click the Test Endpoint button on the API marketplace page, you’ll see the mock response!
Additionally, notice that we have a warning message informing the user that the response is a mock.
Congratulations on creating a mock API! I hope you were surprised by how easy it was.
Conclusion
To be clear, this API is not public, but team members can still access it, provided you add a base URL and some other configuration information.
The example used the UI to create the API and endpoint. However, you may have noticed the different options on the Create New API page. You could choose to use an OpenAPI file, Postman Collection, or GraphQL schema.
Whichever you choose, getting a mock API up and functional can be easy work. Thanks for reading!
FAQs
What are mock APIs?
Mock APIs provide predefined API responses for client applications.
How do you make a mock API?
There multiple ways to create a mock API. A developer may set up an additional server to run locally on their machine. Or, a public mock API is configured using an OpenAPI specification.
What is a mock endpoint?
Mock endpoints have the same name as their real counterpart. Additionally, they return a similar response. The difference is that the interaction is not authentic. The mock endpoint at http://mock.example.com/user is meant to mimic the data http://example.com/user.
How do you mock an API response?
Mocking an API response requires the same pieces that a real API response has. Depending on how you're mocking the API, it's important to provide a status code, any headers, and a response object.
Footnotes
1 Liu, Alex. “The API Dilemma – Choosing a Mock API vs. a Real Backend.” Confluent, www.confluent.io/blog/choosing-between-mock-api-and-real-backend/. Accessed 6 May 2021.
2 For the full list of tools, see Liu above.
Leave a Reply