This tutorial will show you how to create route responses in Mockoon and use the rules system to serve them depending on conditions.
For each of Mockoon’s API endpoints, you can define multiple responses with specific characteristics like status, body, and headers and serve them using a set of rules. In this tutorial, we will create a typical setup: one response returning a 200 status code and another one returning a 401 status code when the "Authorization" header is not present in the request.
The first step is to create a new route by clicking on the blue "Add route" button.
When you create a new endpoint, there is always at least one default response with a 200 status code.
We can customize its body with a simple JSON object.
The next step is to add a second response returning a 401 status code when the "Authorization" header is missing from the request.
To add a new response, click on the blue "plus" button next to the response list.
You can also duplicate a response or delete it by clicking the buttons on the right.
The blue flag in the menu indicates which response will be served by default when no rule matches or when rules are disabled. We will keep the flag on our 200 "success" response.
The next step is to customize our response. Let’s change the status code to 401 "Unauthorized" and add a description: "Error unauthorized". Here too, we can customize the body with a simple JSON object.
The final step is to add a rule on the new response to serve it only when the "Authorization" header is missing.
Click on the rules tab and on the "Add rule" button.
In the new rule, select "Header" and enter "Authorization" as the "Header name".
Finally, select "null" as the value instead of "equals".
You can now test your setup by calling your mock API with and without an Authorization header.
Three options are also available next to the responses list: random, sequential, and rules disabled.
You can randomize the responses with the first option or cycle through them sequentially with the second. Both options will disable the rules. The third option allows you to disable the rules and always serve the default response marked with a blue flag.