Skip to main content

Using path params

Path parameters are a way to include dynamic values in the URL path of a request. They are typically used to identify a resource being accessed or modified. For example, in the URL /users/:userId, :userId represents a path parameter that can be replaced with a specific user identifier when making a request.

Using request path params

Path params are automatically inferred from the paths in your schema. To define a path param, prefix it with a colon (:) in the path string. See Declaring paths for more details on how to declare required, optional, and repeating path params.

schema.ts
import { HttpSchema } from '@zimic/http';

interface User {
id: string;
username: string;
}

type Schema = HttpSchema<{
'/users/:userId': {
PATCH: {
request: {
body: Partial<User>;
};
response: {
204: {};
};
};
};
}>;

Then, the path params of the requests will be available in the pathParams property, such as in handler.with(), computed responses, and handler.requests.

You can use path params directly in the path string using template literals. @zimic/interceptor automatically infers the endpoint and types all resources as usual.

interceptor
.patch(`/users/${user.id}`)
.respond({ status: 204 })
.times(1);

Matching any value

Interceptors accept path params in the path string, declared with a colon (:) as in the schema. This allows you to match any value for that parameter. If you need to escape a colon in the path, use two backslashes before the : (\\:).

By default, path params match a single segment, not including slashes (/). See Declaring paths for more details on how to declare repeating path params, which accept multiple segments.

const handler = interceptor
// Match any user id
.patch('/users/:userId')
.respond((request) => {
console.log(request.pathParams.userId);

return { status: 204 };
})
.times(1);

// Run the application and make requests...

console.log(handler.requests); // 1
console.log(handler.requests[0].pathParams.userId);

Use interceptor.with() in case you need validation or to limit a parameter to specific values.

interceptor
// Match any numeric user id
.patch('/users/:userId')
.with((request) => /^\d+$/.test(request.pathParams.userId))
.respond({ status: 204 })
.times(1);