Skip to main content

How To Match Path Params In Mock APIs

Mock rules are the core component of Beeceptor's mock API capabilities. They enable the matching of incoming requests with predefined responses based on specific criteria, such as query parameters, request paths, HTTP headers, patterns defined by regular expressions, or even multiple conditions using AND operator. In this article, let's dive deeper into the regular expression support when matching requests.

Regular Expressions

Beeceptor's regular expression allows you to match complex request paths, and enable extracting parts of the request path as variables. To use this, create a mock rule that specifies a regular expression as the criterion for matching the request path. Now in the expression textbox, provide the regular expression.

Example: For a mock rule aimed at matching user IDs in a request path, you should use the following regular expression:

/api/users/\d+

This expression matches a sequence of one or more digits for the user entity.

request-path-regular-expression-match

This rule setup matches to all request paths having the format:
https://my-endpoint.proxy.beeceptor.com/api/users/1234

Named Groups: With Beeceptor, you can go further, and include named groups to capture specific segments of the path for later use in the response. These are extracted as variables and available in the response template. This approach provides a flexible way to craft dynamic responses based on the incoming request's specifics. Let's see it in action.

Matching Path Parameters

A common practice in API design is to include entity IDs directly in the API request path, known as path parameters. Beeceptor allows you to match these path parameters using regular expressions and extract them as named variables. This feature is particularly useful for testing APIs that rely on dynamic values within the request URL.

Example: The following regular expression uses a named group. The sequence of one or more digits is named as userID and available as a variable in response.

/api/users/(?<userID>\d+)

For the complete setup of this rule refer below screenshot. Make sure to select the 'Enable dynamic mock responses' checkbox to enable the template engine.

request-path-regular-expression-using-named-groups

This rule setup matches to all request-paths having below format and extracts the entity-id:
https://my-endpoint.proxy.beeceptor.com/api/users/1234

Now when you hit the API URL as https://my-endpoint.proxy.beeceptor.com/api/users/234, you get the following response. Here, the id value is picked from the request path.

{
"id" : "234"
"name": "David"
}

This feature empowers software development teams to fine craft API stubs, facilitating complex scenario simulation and supporting frontend teams when the actual APIs are still under development.