Typegen
An HTTP schema is one of the main aspects of @zimic/http
. It allows you to
define the structure of an API in readable TypeScript types. @zimic/fetch
and
@zimic/interceptor
use these schemas to provide type-safe APIs for sending,
receiving, and mocking requests.
@zimic/http
has typegen support for OpenAPI documentation. The result is a ready-to-use
schema that can be used directly by @zimic/fetch
,
@zimic/interceptor
, and your application code.
OpenAPI
OpenAPI is a specification for defining APIs in a human and machine-readable format. It allows you to describe the structure of your API, including endpoints, request and response types, authentication methods, and more.
To generate a schema from a local OpenAPI document, use the @zimic/http
CLI.
- JSON
- YAML
zimic-http typegen openapi ./schema.json \
--output ./schema.ts \
--service-name MyService
zimic-http typegen openapi ./schema.yaml \
--output ./schema.ts \
--service-name MyService
You can also fetch the OpenAPI documentation from a remote URL:
- JSON
- YAML
zimic-http typegen openapi https://example.com/api/openapi.json \
--output ./schema.ts \
--service-name MyService
zimic-http typegen openapi https://example.com/api/openapi.yaml \
--output ./schema.ts \
--service-name MyService
The output file will contain your HTTP schema, named based on the --service-name
option and including the generated
types for each endpoint.
import { HttpSchema } from '@zimic/http';
export type Schema = HttpSchema<{
users: {
GET: {
request: {
searchParams: { search?: string };
};
response: {
200: {
headers: { 'content-type': 'application/json' };
body: MyServiceComponents['schemas']['Users'];
};
};
};
// ...
};
// ...
}>;
export interface MyServiceComponents {
schemas: {
User: { id: number; name: string };
Users: MyServiceComponents['schemas']['User'][];
// ...
};
// ...
}
export interface MyServiceOperations {
// ...
}
Then, you can use these types in your code, your
@zimic/fetch
clients and
@zimic/interceptor
interceptors.
Examples
Our OpenAPI typegen example shows how the type generation can be used in practice.