DEV Community

Cover image for Designing Restful APIs using an API-First Approach — Mocking
Nicolas Takashi
Nicolas Takashi

Posted on • Updated on • Originally published at nicolastakashi.Medium

Designing Restful APIs using an API-First Approach — Mocking

A few weeks ago, I began a new post series to talk about API-First and API-Design using OpenAPI Specification.

If you didn't see the first post of this series yet, I recommend you stop reading and check it by clicking here.

In today’s post, I will address how to build a Mock Server to improve the developer experience and work parallelism, using OpenAPI documents.

😎 — Mock Concepts

Before we deep dive into Mock techniques using OpenAPI documents, let’s just ensure that everybody knows what Mock means according to Wikipedia.

In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways, most often as part of a software testing initiative. A programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to simulate the dynamic behavior of a human in vehicle impacts. The technique is also applicable in generic programming.

💡— Mock at the HTTP level.

In the API worlds, the concept of mock remains the same described above, but instead of using frameworks to mockup objects such as Moq and RinoMock, this is done using a Mock Server.

The Mock Server will respond to the expected endpoints, error for non-existent endpoints, often even provide realistic validation errors if a client sends it an invalid request.

Mock Server Alternatives

There are a couple of alternatives to create a Mock Server, each one with its trade-offs, below you can check a short options list.

Every option listed above are great tools and definitely works as expected. But the goal of this post is to show how to use the OpenAPI documents to build a mock server.

Bearing it in mind, just Prism provides us a built-in integration with Open-API to create a Mock Server, so we don’t need to write any code to do that.

🙌 — Introduction to Prism

Prism is a command-line interface that aggregates a set of packages for API Mocking using OpenAPI documents, this was developed using JavaScript and NodeJS, there are a huge community and many stars on Github Repository.

Getting Started

In the last post, I used a Github Repository with the code of the post series, so let’s keep working on top of that and evolves the solution.

Now let's add Prism to the project using some of the commands below.

yarn add @stoplight/prism-cli
# or
npm install --save @stoplight/prism-cli
Enter fullscreen mode Exit fullscreen mode

Prism’s HTTP mock server simulates a real web API by providing endpoints and validation rules described in your API description document, like any HTTP solution, it works around the Request Messages and Response Messages.

Response Generation

Prism will try to return meaningful responses based on whatever information it has available, this means that any OpenAPI document can be used, but better documents provide better results. If you want to know how the prism decision engine works for response generation, you can check this link.

Response Generation Strategies

Prism has two response generation strategies, static generation, and dynamic generation, there are several differences between those options that we will understand right now.

Static Generation Strategy

By default, Prism will use a static generation strategy to create a response message, to use it, you can run the command below.

prism mock <path-to-openapi>
Enter fullscreen mode Exit fullscreen mode

If the provided OpenAPI document has a response body example then it’ll use that, otherwise, the response body will be created by looking through the whole schema object to create a fake response.

Dynamic Generation Strategy

Testing against the exact same piece of data over and over again is not the best way to build a robust API, in the real world the data is dynamic and we must be able to handle it properly, you can run the command below.

prism mock <path-to-openapi> -d
Enter fullscreen mode Exit fullscreen mode

Dynamic mode solves this by generating a random value for all the properties according to their type, and other information like format, this means that the more descriptive your API is, the better job Prism can do at creating a mock response.

Request Validation

Based on the API description document Prism can take into consideration all sorts of validation rules for the request body, headers, query parameters, using keywords like type, format, maxLength.

👊 — Introduction to Prism

Now you know the Prism basics and how it works, let's configure it in our API project and start a new mock server.
First of all, we need to change the package.json to looks like the example below, with two new commands mock and premock.

  "name": "todoapi-spec",
  "version": "1.0.0",
  "description": "OpenAPI specification for TodoAPI",
  "main": "index.js",
  "author": "Nicolas Takashi",
  "license": "MIT",
  "scripts": {
    "premock": "yarn bundle",
    "mock": "prism mock ./bin/api.yaml -d",
    "bundle": "swagger-cli bundle specs/api.yaml -o ./bin/api.yaml -t yaml",
    "prelint": "yarn bundle",
    "lint": "spectral lint ./bin/api.yaml --ignore-unknown-format"
  "dependencies": {
    "@openapitools/openapi-generator-cli": "^1.0.15-4.3.1",
    "@stoplight/prism-cli": "^4.0.0",
    "@stoplight/spectral": "^5.5.0",
    "swagger-cli": "^4.0.4"
Enter fullscreen mode Exit fullscreen mode

Now, just run the command below to start the Prism, and look to the console to see the output.

yarn mock
Enter fullscreen mode Exit fullscreen mode

If we look to the console output, there is a Mock Server running through the localhost:4010, and from now, we are able to make API calls to this Prism Server.

Prism Console Output

Making an API Call with Swagger UI

Let's make a request call through the Swagger UI, but before you do that, change the api.yaml and add the servers section, like the example below.

openapi: 3.0.0
  title: Todo App API
  description: Todo App API.
  version: v1
    email: ''
    name: 'Nicolas Takashi'
  - url:
    description: Mock Server
  - name: Tasks
    $ref: './components/paths/tasks/task.yaml'
    $ref: './components/paths/tasks/task-by-id.yaml'
      $ref: 'components/schemas/task.yaml#/components/schemas/Task'
      $ref: 'components/schemas/pagedTask.yaml#/components/schemas/PagedTask'
      $ref: 'components/schemas/problemDetails.yaml#/components/schemas/ProblemDetails'
Enter fullscreen mode Exit fullscreen mode

Now if we look to the Swagger UI, we will notice a new drop-down with a list of available servers, such as the image below.

Swagger UI — Server List

Last but not least, let’s try to create a task, calling the POST /tasks and looks at the output.

Success Request

Since the name is required and we sent this property, the request returns an HTTP Created 201 with the location header, as you can see in the image below.

Create a new task with valid parameters

Invalid Request

After tried to create a task without a name, we get back the HTTP Bad Request, as described in the OpenAPI document.
Create a new task with invalid parameters


That’s all for today, now you have the basics about the Mock APIs, I really recommend you to check the Prism official documentation, to understand every feature and how to deploy it to your clients take advantage of this strategy.

API Mock can anticipate so many problems that could exist between APIs consumption and system integrations.

You can check the project on Github, everything is updated with the implementations that we did in this post.

I hope you enjoyed it, please let me know your feedback, comment below, and share with your friends.

Top comments (0)