When mocking a real API, it's likely that we'd want our routes to accept dynamic parameters, for instance: /users/1 or /users/2, and for our mock API to understand this. Fortunately, Mockfly recognizes and assists with this.
To incorporate dynamic parameters in the URL, we'll utilize a common syntax to indicate that a parameter can be dynamic. For instance, in the route /users/2, the number two signifies the user ID, implying that our mock API might receive any value. To make our endpoint accept dynamic parameters, we should define the route as: /users/:id.
We can define the parameter with any name, for example: /users/:foo or /users/:bar. It's also crucial to note that we can have as many parameters as needed. For instance, in the URL: /orders/123/returns/456, we could make it dynamic by defining the URL as: /orders/:orderId/returns/:returnId, this way, it would accept the dynamic parameters of that URL.
It's essential to have unique names since we might want to use these parameters in the response body. We'll use the same name to do so (explained in the subsequent section). Moreover, it's worth noting that this only works for parameters in the URL and not for query params.
To make our mock API more realistic, we can have the API return the parameters that we defined as dynamic in the URL. For example, for the URL /users/:id, we might want our mock API response to be a user object with the id passed in the URL. Doing this is straightforward:
{
"id": "{{:id}},
"name": "John"
}
With this setup, our mock API will replace the {{:id}} with the id provided as a parameter in the URL. We should always use the same name as given in the URL; otherwise, Mockfly won't replace anything.
Create a project