Mock APIs are invaluable tools for developers to simulate real-world API endpoints during development and testing phases. Mockoon is a powerful desktop application that simplifies the creation and management of mock REST APIs. Combined with Faker.js, you can generate complex and dynamic fake data to mimic real API responses. In this article, we'll walk through designing a mock REST API using Mockoon, utilize Faker.js for generating complex data, and deploy the mock API in a Docker container using the Mockoon CLI.
Table of Contents
- Introduction to Mockoon and Faker.js
- Prerequisites
- Designing a Mock REST API with Mockoon
- Testing the Mock API Locally
- Exporting the Mockoon Environment
- Deploying the Mock API in a Docker Container
- Advanced Configuration
- Conclusion
1. Introduction to Mockoon and Faker.js
- Mockoon: An intuitive desktop application for designing mock REST APIs. It offers a user-friendly interface to create environments, routes, and responses without writing any code.
- Faker.js: A JavaScript library that generates massive amounts of fake data for testing and development purposes. It can produce random names, addresses, company data, images, and much more.
By integrating Faker.js within Mockoon, you can generate dynamic and realistic data responses, enhancing the simulation of real-world APIs.
2. Prerequisites
- Mockoon Desktop Application: Download and install from Mockoon's website.
- Docker: Install Docker Desktop from Docker's official site.
- Node.js and npm: Required for the Mockoon CLI. Download from Node.js official site.
- Basic Understanding: Familiarity with REST APIs, JSON, and command-line operations.
3. Designing a Mock REST API with Mockoon
Creating a New Environment
- Launch Mockoon: Open the Mockoon desktop application.
- Create Environment: Click on "New environment" in the top-left corner.
- Name the Environment: Double-click the environment name (e.g., "New environment") and rename it to "User API".
- Set the Port: Ensure the port does not conflict with existing services (default is 3000).
Import OpenAPI File:
- Go to File > Import OpenAPI specification.
- Select your
.yaml
or.json
OpenAPI file. - Mockoon will automatically create routes and responses based on the OpenAPI specification.
-
Review Routes:
- Mockoon will generate API endpoints, methods, and sample responses. You can edit these if needed. For example:
- Add dynamic responses using Handlebars templating.
- Simulate delays or errors.
- Mockoon will generate API endpoints, methods, and sample responses. You can edit these if needed. For example:
Adding Routes and Endpoints
- Add a Route: Click on "Add a route".
-
Configure the Route:
- Method: Select GET.
-
Endpoint: Enter
/users
. - Route Name: Rename to "Get Users".
-
Set the Response:
-
Content-Type: Ensure it is set to
application/json
. - Body: We will use Faker.js templating here.
-
Content-Type: Ensure it is set to
Using Faker.js for Dynamic Data
Mockoon supports templating with Faker.js through Handlebars syntax.
- Generate a List of Users:
Replace the response body with the following code:
[
{{#repeat 10}}
{
"id": "{{faker.datatype.uuid}}",
"name": "{{faker.name.firstName}} {{faker.name.lastName}}",
"email": "{{faker.internet.email}}",
"address": {
"street": "{{faker.address.streetAddress}}",
"city": "{{faker.address.city}}",
"country": "{{faker.address.country}}"
},
"company": "{{faker.company.companyName}}",
"profilePic": "{{faker.image.avatar}}",
"registeredAt": "{{faker.date.past}}"
}{{#unless @last}},{{/unless}}
{{/repeat}}
]
Explanation:
-
{{#repeat 10}}...{{/repeat}}
: Repeats the enclosed block 10 times to generate 10 user objects. - Faker.js Functions: Used to generate random data for each user.
- Add Another Route for User Details:
- Method: GET
-
Endpoint:
/users/:id
- Route Name: "Get User By ID"
-
Response Body:
{ "id": "{{urlParam 'id'}}", "name": "{{faker.name.firstName}} {{faker.name.lastName}}", "email": "{{faker.internet.email}}", "phone": "{{faker.phone.phoneNumber}}", "bio": "{{faker.lorem.paragraphs}}", "interests": [ {{#repeat (faker.datatype.number 5)}} "{{faker.hobby.hobby}}"{{#unless @last}},{{/unless}} {{/repeat}} ] }
Explanation:
-
{{urlParam 'id'}}
: Retrieves theid
parameter from the URL. - Dynamic Interests: Generates a random number of hobbies.
-
** Dynamic Responses with Handlebars Templating**
Mockoon supports Handlebars templating to create dynamic responses based on variables or request data. This is especially useful when you want your API to respond differently based on input.
- Example: Dynamic User Response:
{
"id": "{{faker.datatype.uuid}}",
"name": "{{faker.name.firstName}} {{faker.name.lastName}}",
"email": "{{faker.internet.email}}",
"address": {
"city": "{{faker.address.city}}",
"country": "{{faker.address.country}}"
},
"requestedId": "{{queryParam 'id'}}"
}
-
{{faker.*}}
: Generates random fake data (e.g., UUIDs, names, emails, etc.). -
{{queryParam 'id'}}
: Retrieves the query parameterid
from the incoming request.
** Simulate Delays**
To test how your application handles slow responses:
-
Add a Delay:
- In Mockoon, go to the route settings and set a delay (e.g., 1000ms).
-
Test the Behavior:
- Simulate network latency to see how your frontend or client handles slow API responses.
3. Error Responses
You can simulate error scenarios by creating additional routes or using conditional Handlebars logic.
-
Example: Simulate a 404 Error:
Add a route with
GET /users/:id
and use the following response:
{{#if (equals urlParam 'id' '123')}}
{
"id": "123",
"name": "John Doe"
}
{{else}}
{
"error": "User not found"
}
{{/if}}
4. Testing the Mock API Locally
- Start the Environment: Click on the green "Play" button in the top toolbar.
-
Test the Endpoints:
-
Get Users: Visit
http://localhost:3000/users
in your browser or use a tool like Postman or curl. -
Get User By ID: Visit
http://localhost:3000/users/1234
, replacing1234
with any identifier.
-
Get Users: Visit
You should see JSON responses with dynamically generated data.
5. Exporting the Mockoon Environment
To deploy the mock API outside of the desktop application, you need to export the environment.
-
Export Environment:
- Go to
File
>Export current environment
. - Save the file as
user-api-environment.json
in your project directory.
- Go to
6. Deploying the Mock API in a Docker Container
Setting Up the Dockerfile
-
Create a Project Directory:
- Open your terminal and create a new directory:
mkdir mockoon-docker cd mockoon-docker
-
Move the Environment File:
- Copy
user-api-environment.json
intomockoon-docker
directory.
- Copy
-
Create a Dockerfile:
- In
mockoon-docker
, create a file namedDockerfile
with the following content:
# Use the official Node.js LTS image FROM node:18-alpine # Install Mockoon CLI globally RUN npm install -g @mockoon/cli # Create a directory for the app WORKDIR /app # Copy the environment file into the container COPY user-api-environment.json /app/user-api-environment.json # Expose the port (make sure it matches your Mockoon environment port) EXPOSE 3000 # Start the Mockoon CLI with the environment file CMD ["mockoon-cli", "start", "--data", "/app/user-api-environment.json", "--hostname", "0.0.0.0"]
Explanation:
- In
- **`node:18-alpine`**: A lightweight Node.js image based on Alpine Linux.
- **Installing Mockoon CLI**: Required to run the mock API from the environment file.
- **Setting the Hostname**: **`0.0.0.0`** allows Docker to expose the service outside the container.
Building and Running the Docker Image
- Build the Docker Image:
docker build -t mockoon-user-api .
-
-t mockoon-user-api
: Tags the image with the namemockoon-user-api
. - The dot
.
specifies the current directory as the build context.
Run the Container with the Environment File:
Pass the file path dynamically using the -v
(volume) and -e
(environment) flags:
docker run -d \
-p 3000:3000 \
-v /path/to/api-environment.json:/app/api-environment.json \
-e MOCK_ENV_FILE=/app/api-environment.json \
mockoon-dynamic
Explanation:
-
-v /path/to/api-environment.json:/app/api-environment.json
: Mounts the environment file from your local machine into the container. -
-e MOCK_ENV_FILE=/app/api-environment.json
: Sets theMOCK_ENV_FILE
environment variable to the path of the mounted file.
-
Test the Deployed Mock API:
- Access the mock endpoints at
http://localhost:3000
.
- Access the mock endpoints at
Test the Endpoints:
-
Get Users: Visit
http://localhost:3000/users
. -
Get User By ID: Visit
http://localhost:3000/users/1234
.
The mock API is now running inside a Docker container, accessible on your local machine.
7. Advanced Configuration
Environment Variables
You can make your mock API more flexible by using environment variables.
Setting Up Environment Variables in Mockoon
- Define Environment Variables:
In Mockoon, click on the "Environment Settings" (gear icon) and add variables under the "Environment variables" section.
Example:
-
API_VERSION
:v1
-
MAX_USERS
:20
- Use Variables in Routes:
Modify the /users
endpoint response body:
[
{{#repeat (env 'MAX_USERS')}}
{
"id": "{{faker.datatype.uuid}}",
"version": "{{env 'API_VERSION'}}",
"name": "{{faker.name.firstName}} {{faker.name.lastName}}"
{{!-- ... other fields --}}
}{{#unless @last}},{{/unless}}
{{/repeat}}
]
Passing Environment Variables to Docker
Modify the CMD
in your Dockerfile
to pass environment variables:
CMD ["sh", "-c", "mockoon-cli start --data /app/user-api-environment.json --hostname 0.0.0.0 --env-var API_VERSION=v1 --env-var MAX_USERS=20"]
Alternatively, set them at runtime:
docker run -d -p 3000:3000 \
-e API_VERSION=v2 \
-e MAX_USERS=50 \
mockoon-user-api
HTTPS and Certificates
If your application requires HTTPS:
- Generate Self-Signed Certificates (for testing purposes):
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
- Copy Certificates into the Container:
Modify the Dockerfile
:
# Copy certificates
COPY cert.pem /app/cert.pem
COPY key.pem /app/key.pem
- Start Mockoon with HTTPS Options:
Modify the CMD
:
CMD ["mockoon-cli", "start", "--data", "/app/user-api-environment.json", "--hostname", "0.0.0.0", "--tls", "--tls-cert", "/app/cert.pem", "--tls-key", "/app/key.pem"]
- Update Environment Settings in Mockoon:
- In Mockoon, enable "HTTPS" in the environment settings.
- Set the port appropriately (e.g.,
443
).
- Run the Docker Container:
Expose the HTTPS port:
docker run -d -p 443:443 mockoon-user-api
8. Conclusion
By integrating Mockoon with Faker.js, you can create sophisticated mock REST APIs featuring dynamic and complex data. Deploying these APIs in Docker containers using the Mockoon CLI allows for consistent and portable environments suitable for development, testing, and CI/CD pipelines.
Benefits:
- Scalability: Run multiple instances or different APIs simultaneously.
- Consistency: Ensure the same environment across different machines and team members.
- Automation: Integrate into automated testing workflows.
Next Steps:
- Explore Mockoon's templating capabilities further, including conditional responses and advanced Handlebars helpers.
- Integrate the mock API into your CI/CD pipeline for automated testing.
- Utilize Docker Compose to manage multiple mock services and dependent containers.
Resources:
- Mockoon Official Documentation
- Faker.js Documentation
- Docker Documentation
- Handlebars.js Documentation
Happy mocking and efficient testing!
Top comments (0)