This is the site's logo
This is the site's logo
Published on

Dynamic Mock Server with OpenAPI

Authors

image1

Mock server enables easy mocking of any system you integrate with via HTTP or HTTPS with clients allowing asycronus development between frontend, backend and stakeholders having early feedback without writing a line of code. When we separate frontend and backend, we create a dependency issue. Usually backend needs to build first before the frontend, althought there are some options to get a workaround, most of them will pullute the frontend with mock data.

The approach we are going to tackle in this article is the mock server setup which is the cleanest one but with some trade-offs, one of the most relevant trade-offs is that we can't write logic in our mock server.

To build our OpenAPI based mock server, we are going to use a tool called Prism. Prism is an open-source HTTP mock server that can emulate an API behavior generated from a v2/v3 OpenAPI specification.

Setting up Prism

Installation

Prism is a NodeJS Command Line Interface (CLI) tool.It provides mocking, request validation, and content negotation. Prism requires

  • NodeJS >= 16
  • for NodeJS 18.x, >= 18.16

You can install Prism using de following command:

npm install -g @spotlight/prism-cli

You should now be able to run prism --help, which prints out usage information. If that doesn't work, try restarting your terminal.

If you're in a UNIX system you can run:

exec -l bash # or zsh, whatever shell you're running on"

To test Prism, wewill need an OpenAPI definition. You can go to this repo https://github.com/Grifo89/users-openapi and grap the OAS called users.oas.yml and store it locally, open the directory you stored the file in the terminal and run:

prism mock -p 8010 ./users.oas.yml

That should throw an output like the following:

❯ prism mock -p 8010 ./users.oas.yml
[CLI] …  awaiting  Starting Prism…
[CLI] ℹ  info      GET        http://127.0.0.1:8010/users
[CLI] ℹ  info      POST       http://127.0.0.1:8010/users
[CLI] ℹ  info      GET        http://127.0.0.1:8010/users/c976ac8d-9eff-0d89-8daa-ad2954a42c5b
[CLI] ℹ  info      PUT        http://127.0.0.1:8010/users/7117d06c-b4f9-6dd7-a668-668bd6a578e3
[CLI] ℹ  info      DELETE     http://127.0.0.1:8010/users/06a45cbd-b77b-e24e-1916-cb6f0e2f90d3
[CLI] ▶  start     Prism is listening on http://127.0.0.1:8010

The response of the mock server will be the examples you provided on the OpenAPI specification, so don't forget to include examples for each endpoint!

Conclusion

Voila! 🚀🎉, now we have our mock server up and running, ready to help our development process. That's all for this entry, hope this might be helpful to you and your team. Mock server help us as a tool for continuous integration and it's good practice consider it at the development process.