Set up a mock API in 2 minutes
In this article, I’ll explain how you can quickly transform a JSON file into a mock API only using Docker.
I recently implemented a mock API using Mockserver. While it is a powerful tool that can be run in multiple programming languages the documentation does contain a straightforward guide on how to get set up. This article is primarily a summary of the official docs that will let you get set up faster.
tldr;
Step 1: Create an expactations.json
file that will contain the endpoints you want to mock and the expected response
Step 2: Passing the expectations.json
file to the official Mockserver Docker image when running it using the following command:
docker run --rm --name=mockserver -p 1080:1080 \
-v $(pwd)/expectations.json:/config/expectations.json \
-e MOCKSERVER_INITIALIZATION_JSON_PATH=/config/expectations.json \
mockserver/mockserver \
-serverPort 1080 \
-logLevel INFO
How to run Mockserver
I wanted to follow a simple and generic implementation so I ran Mockserver using Docker and configured expectations using JSON files.
The expectations JSON file is what makes Mockserver so simple and reusable. It removes any dependency on knowledge of a particular programming language or a requirement to install any packages to set up the server. As long as you already have Docker installed you are good to go.
Once you define the expected request path, desired response body and status code you are ready to go. There is a basic example below but you can find many more on the Mockserver Github Repo.
[
{
"httpRequest": {
"path": "/somePathOne"
},
"httpResponse": {
"statusCode": 200,
"body": {
"value": "one"
}
}
}
]
To pass a JSON file to a MockServer running in a Docker container, you can use Docker’s volume mounting feature. This allows you to make a file or directory on the host machine accessible inside the Docker container.
Assuming your expectations file is named expectations.json
you can run the MockServer Docker container with a command like this:
docker run --rm --name=mockserver -p 1080:1080 \
-v $(pwd)/expectations.json:/config/expectations.json \
-e MOCKSERVER_INITIALIZATION_JSON_PATH=/config/expectations.json \
mockserver/mockserver \
-serverPort 1080 \
-logLevel INFO
In this command:
-v $(pwd)/expectations.json:/config/expectations.json
mounts theexpectations.json
file from the current directory on the host machine to/config/expectations.json
inside the container.-e MOCKSERVER_INITIALIZATION_JSON_PATH=/config/expectations.json
is needed for Mockserver to load the expectations automatically once it has been mounted to the container-p 1080:1080
maps port 1080 in the container to port 1080 on the host machine.-serverPort 1080
sets the MockServer to listen on port 1080.-logLevel INFO
sets the log level to INFO.
You can now visit http:localhost:1080/somePathOne
in your browser or run curl http:localhost:1080/somePathOne
to interact with it via the CLI.