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.

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.

const handler = interceptor
.patch(`/users/${user.id}`)
.with({ body: { username: 'new-username' } })
.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);

Matching multiple path params

To match any value in a path param, declare it with a colon (:) in the path string, such as /users/:userId.

const handler = interceptor
// Match any user id
.patch('/users/:userId')
.with({ body: { username: 'new-username' } })
.respond({ status: 204 })
.times(1);

interceptor.with() is useful in case you want to validate the parameter or limit it specific values.

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