What is API mocking?


This is a guest post written by Allen Helton, ecosystem engineer at Momento.

Software development has never moved faster than it does today. User expectations and time-to-market have both skyrocketed in recent years due to accelerated cloud adoption and innovations in the industry.

These rising expectations have forced development teams to take drastic measures. For instance, it’s no longer uncommon to see frontend development running in tandem with backend service development. Now, you might be scratching your head and wondering, “How do they do that?” You can only get so far building a user interface before you need to call some APIs.

Sure, you can hardcode JSON objects in your web components to simulate the response you’d get from a would-be service call, but that approach doesn’t provide you with enough flexibility. You need to handle edge cases, error scenarios, and other successful calls.

The answer is simple: API mocking.

What is an API mock?

An API mock is a web service that simulates a real, functional service. A mock can be used to provide example responses from the backend service that is currently being developed, which makes it a great fit for the use case we described above. Assuming you’re practicing API-first development, your API spec should be complete before any development begins. This means you know all the endpoints, request bodies, and expected responses for every call you need to make.

API mocks can take that information and return data that matches the spec exactly. That way, you can build your service calls from the get-go and swap out the mock URL for the real thing when it’s done. If you’ve taken this into consideration when building your development plan, it could be as simple as swapping out an environment variable.

We now understand that an API mock is a real service that returns data matching the schema of another service. It can return both a variety of successful responses and error scenarios. A mock could represent an entire API or a single endpoint; it depends entirely on your use case.

Common API mocking patterns

API mocks have many benefits that go beyond enabling frontend developers to move faster. There are a surprising number of uses for them across the various stages of the development lifecycle.

Third-party services

Most modern software interacts with at least one third-party service, such as a payment service like Stripe, a caching service like Momento, or a messaging service like Twilio. During backend development, we don’t always want to make real calls to these services. They often incur costs on a per-invocation basis, and you also don’t want to dirty up your environment by pushing large amounts of test data into them.

An API mock can be used in the early stages of development to simulate calls to these services. The mock data can be used to test your development workflows and keep your service environment clean. You can also use the mock to return errors in your code to simulate service outages, which will help you test your application’s overall resilience by seeing how it tolerates uncontrollable faults in external systems.

End-to-end test building

Rapid development cycles often require teams to use continuous integration and continuous delivery (CI/CD) pipelines to push changes to production as soon as they are ready. These pipelines rely on functional tests—such as unit tests, integration tests, and end-to-end tests—to guarantee the latest change doesn’t break backwards compatibility. End-to-end tests focus on validating business workflows that make multiple API calls. If you have your entire API mocked from your spec, you can and should build these tests against the mock.

With Postman, you can build your business workflows into a collection as a series of requests, chaining results from one response into the parameters of the next. Each request calls the mock and asserts that the response status codes and schemas are correct. As development progresses, you swap out the mocks for the real endpoints. If any of your assertions fail, you’ve found a bug in the code.

Once the development of all your endpoints is complete, you already have functioning end-to-end tests to lean on in your pipelines.

Faster DX iterations

Not all APIs have a user interface on top of them. In fact, many services don’t have a UI at all. Instead of focusing on a friendly UI, service developers pour their energy into building a world-class developer experience (DX).

Developer experience is exactly what it sounds like: it qualifies how easy and intuitive it is to use your API. An API mock will let beta testers try to integrate with your service extremely early in the design phase. This approach opens the doors to questions like, “Why isn’t this data returned in call XYZ,” “How do I find my ABC settings,” and “Shouldn’t this just be a single API call?”

Getting these questions before you write any code is important because it provides invaluable feedback that can help shape the product with a minimal amount of rework.

Using Postman for API mocking

Postman has native support for API mocking. You can select an existing collection and it will generate a mock server for you. Using the requests and example responses, the mock server can be extended to return a variety of successes and failures.

Upon successful creation of a mock server, you will receive a URL that you can immediately use to make requests. The mock server will use data from the request to know what type of response to return. This means you can control if you’ll get a success or a failure back based on the data in your request body. This type of inferred flexibility lets you build strong tests around your soon-to-be API because you can force it to respond with any type of response on a whim.

Testing to see how your app responds to a 429 Too Many Requests error? No problem. What about building your UI in a way that gracefully handles a 500 Internal Server Error? Piece of cake.

Things to know before you build

You might have caught earlier that I said a mock server uses a collection—rather than an API spec—to build the mock server. You can’t build a mock pointed directly at a spec.

Luckily, Postman has the ability to generate a collection from a spec. However, mocks can’t be built from a collection linked to an API spec. So, after you generate your collection from your spec, you’ll need to duplicate it to a “freestanding collection” that’s not associated with your API.

Once duplicated, then you can create your mock server. If you make changes to the collection, the mock server will immediately update its responses to match, so you can keep up the rapid iterations.

If you’re making changes to your API spec and related schemas, I wouldn’t recommend updating the mock collection. Update the spec, generate the collection, and then create the mock server from the generated collection. This way, you aren’t manually updating schemas in multiple places.

Try it out

The rapid pace of modern software development makes mock servers a necessity. They provide so much value in all phases of the software development lifecycle. From product design, parallel building of your UI and API, and end-to-end testing, mock servers play a unique role in helping you deploy to production quickly and safely.

If you’re interested in trying out Postman mocks but aren’t sure where to start, I built a collection in my public workspace that takes a JSON object, creates an API spec from it, and then creates a mock server based on the spec. You can go from idea to functional mock in literally 15 seconds. Read my blog post about it for more details.

I hope you try out this underutilized Postman feature. It truly is an accelerator and unlocks a tremendous amount of potential for your API. Whether you’re mocking an API you’re building or one you’re integrating with, you’re sure to learn a few lessons and make important API design decisions earlier than ever before.

Happy coding!

What do you think about this topic? Tell us in a comment below.


Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.