DEV Community

DEV-AI
DEV-AI

Posted on

Using Mockoon to Design and Deploy Mock REST APIs with OpenAPI and Docker

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

  1. Introduction to Mockoon and Faker.js
  2. Prerequisites
  3. Designing a Mock REST API with Mockoon
  4. Testing the Mock API Locally
  5. Exporting the Mockoon Environment
  6. Deploying the Mock API in a Docker Container
  7. Advanced Configuration
  8. 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

  1. Launch Mockoon: Open the Mockoon desktop application.
  2. Create Environment: Click on "New environment" in the top-left corner.
  3. Name the Environment: Double-click the environment name (e.g., "New environment") and rename it to "User API".
  4. 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.
  1. 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.

Adding Routes and Endpoints

  1. Add a Route: Click on "Add a route".
  2. Configure the Route:
    • Method: Select GET.
    • Endpoint: Enter /users.
    • Route Name: Rename to "Get Users".
  3. Set the Response:
    • Content-Type: Ensure it is set to application/json.
    • Body: We will use Faker.js templating here.

Using Faker.js for Dynamic Data

Mockoon supports templating with Faker.js through Handlebars syntax.

  1. 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}}
   ]
Enter fullscreen mode Exit fullscreen mode

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.
  1. 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 the id 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'}}"
  }
Enter fullscreen mode Exit fullscreen mode
  • {{faker.*}}: Generates random fake data (e.g., UUIDs, names, emails, etc.).
  • {{queryParam 'id'}}: Retrieves the query parameter id from the incoming request.

** Simulate Delays**

To test how your application handles slow responses:

  1. Add a Delay:

    • In Mockoon, go to the route settings and set a delay (e.g., 1000ms).
  2. 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}}
Enter fullscreen mode Exit fullscreen mode


4. Testing the Mock API Locally

  1. Start the Environment: Click on the green "Play" button in the top toolbar.
  2. 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, replacing 1234 with any identifier.

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.

  1. Export Environment:
    • Go to File > Export current environment.
    • Save the file as user-api-environment.json in your project directory.

6. Deploying the Mock API in a Docker Container

Setting Up the Dockerfile

  1. Create a Project Directory:

    • Open your terminal and create a new directory:
     mkdir mockoon-docker
     cd mockoon-docker
    
  2. Move the Environment File:

    • Copy user-api-environment.json into mockoon-docker directory.
  3. Create a Dockerfile:

    • In mockoon-docker, create a file named Dockerfile 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:

 - **`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.
Enter fullscreen mode Exit fullscreen mode

Building and Running the Docker Image

  1. Build the Docker Image:
   docker build -t mockoon-user-api .
Enter fullscreen mode Exit fullscreen mode
  • -t mockoon-user-api: Tags the image with the name mockoon-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
Enter fullscreen mode Exit fullscreen mode

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 the MOCK_ENV_FILE environment variable to the path of the mounted file.
  1. Test the Deployed Mock API:

    • Access the mock endpoints at http://localhost:3000.
  2. 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

  1. 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
  1. 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}}
   ]
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

Alternatively, set them at runtime:

docker run -d -p 3000:3000 \
  -e API_VERSION=v2 \
  -e MAX_USERS=50 \
  mockoon-user-api
Enter fullscreen mode Exit fullscreen mode

HTTPS and Certificates

If your application requires HTTPS:

  1. Generate Self-Signed Certificates (for testing purposes):
   openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
Enter fullscreen mode Exit fullscreen mode
  1. Copy Certificates into the Container:

Modify the Dockerfile:

   # Copy certificates
   COPY cert.pem /app/cert.pem
   COPY key.pem /app/key.pem
Enter fullscreen mode Exit fullscreen mode
  1. 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"]
Enter fullscreen mode Exit fullscreen mode
  1. Update Environment Settings in Mockoon:
  • In Mockoon, enable "HTTPS" in the environment settings.
  • Set the port appropriately (e.g., 443).
  1. Run the Docker Container:

Expose the HTTPS port:

   docker run -d -p 443:443 mockoon-user-api
Enter fullscreen mode Exit fullscreen mode

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:


Happy mocking and efficient testing!

Top comments (0)