https://github.com/moznion/openapi-fetch-gen
Generate TypeScript API client from OpenAPI TypeScript interface definitions created by openapi-typescript (https://github.com/openapi-ts/openapi-typescript).
https://github.com/moznion/openapi-fetch-gen
generator openapi openapi-fetch openapi-typescript typescript
Last synced: 13 days ago
JSON representation
Generate TypeScript API client from OpenAPI TypeScript interface definitions created by openapi-typescript (https://github.com/openapi-ts/openapi-typescript).
- Host: GitHub
- URL: https://github.com/moznion/openapi-fetch-gen
- Owner: moznion
- License: mit
- Created: 2025-04-17T08:01:17.000Z (about 1 month ago)
- Default Branch: main
- Last Pushed: 2025-05-12T16:54:37.000Z (13 days ago)
- Last Synced: 2025-05-12T17:59:02.940Z (13 days ago)
- Topics: generator, openapi, openapi-fetch, openapi-typescript, typescript
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/@moznion/openapi-fetch-gen
- Size: 209 KB
- Stars: 14
- Watchers: 1
- Forks: 1
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# openapi-fetch-gen [](https://github.com/moznion/openapi-fetch-gen/actions/workflows/test.yml)
Generate TypeScript API client from OpenAPI TypeScript interface definitions created by [openapi-typescript](https://github.com/openapi-ts/openapi-typescript).
This tool takes TypeScript interface definitions generated by `openapi-typescript` and creates a fully typed API client using [openapi-fetch](https://github.com/openapi-ts/openapi-typescript/tree/main/packages/openapi-fetch).
## How It Works
1. Parse the TypeScript schema file generated by `openapi-typescript`
2. Extract all API endpoints, their HTTP methods, and parameter structures from the schema
3. Generate typed wrapper functions for each endpoint
4. Export a fully-typed client that provides:
- A base client instance created with `createClient` from `openapi-fetch`
- Individual typed functions for each API endpoint
- Type helpers for parameters and responses## Installation
```bash
npm install --save-dev @moznion/openapi-fetch-gen
```## Usage
### CLI
```bash
npx openapi-fetch-gen --input ./schema.d.ts --output ./client.ts
```Options:
```
-V, --version output the version number
-i, --input path to input OpenAPI TypeScript definition file
-o, --output path to output generated client file (default: "./client.ts")
-h, --help display help for command
```### Example
Please refer to the [examples](./examples/).
`schema.d.ts` is generated from `schema.yaml` by `openapi-typescript`, and `generated_client.ts` is generated by this tool according to the `schema.d.ts`.
FYI, you can use the generated client as follows:
```typescript
import { Client } from "./generated_client";async function doSomething() {
const client = new Client({ baseUrl: "https://api.example.com" });
const users = await client.getUsers({
query: {
page: 1,
pageSize: 10,
membershipType: "PREMIUM",
},
});for (const user of users.data?.items ?? []) {
console.log(`User: ${user.name}, Email: ${user.email}`);
}
}
```### Default HTTP Headers
Generated clients support a generic type for default HTTP headers.
Example:
```typescript
export class Client> {
constructor(clientOptions: ClientOptions, defaultHeaders?: HT) {
this.client = createClient(clientOptions);
this.defaultHeaders = defaultHeaders ?? ({} as HT);
}
...
}
```You can create a client instance with default headers like this:
```typescript
new Client({}, {"Authorization": "Bearer your-token", "Application-Version": "1.0.0"});
```With this setup, endpoint methods that require these headers no longer need them to be explicitly passed each time.
For example, given the following schema:
```typescript
"/users/bulk/{jobId}": {
get: {
parameters: {
query?: never;
header: {
/** @description Authorization Header */
Authorization: string;
/** @description Application version */
"Application-Version": string;
/** @description Identifier of something */
"Something-Id": string;
};
path: {
/** @description Bulk import job identifier */
jobId: string;
};
cookie?: never;
};
```This tool generates an endpoint method using a type-level trick like this:
```typescript
async getUsersBulkJobid(
params: [
Exclude<
// Missed Header Keys for default headers
keyof {
Authorization: string;
"Application-Version": string;
"Something-Id": string;
},
Extract<
// Provided header keys by default headers' keys
keyof HT,
keyof {
Authorization: string;
"Application-Version": string;
"Something-Id": string;
}
>
>,
] extends [never]
? {
header?: {
Authorization: string;
"Application-Version": string;
"Something-Id": string;
};
path: { jobId: string };
}
: {
header:
| (Pick<
// Pick the header keys that are not in the default headers
{
Authorization: string;
"Application-Version": string;
"Something-Id": string;
},
Exclude<
// Missed Header Keys for default headers
keyof {
Authorization: string;
"Application-Version": string;
"Something-Id": string;
},
Extract<
// Provided header keys by default headers' keys
keyof HT,
keyof {
Authorization: string;
"Application-Version": string;
"Something-Id": string;
}
>
>
> &
Partial<
// Disallow default headers' keys to be in the header param
Record<
Extract<
// Provided header keys by default headers' keys
keyof HT,
keyof {
Authorization: string;
"Application-Version": string;
"Something-Id": string;
}
>,
never
>
>)
| {
Authorization: string;
"Application-Version": string;
"Something-Id": string;
};
path: { jobId: string };
},
) {
return await this.client.GET("/users/bulk/{jobId}", {
params: {
...params,
header: { ...this.defaultHeaders, ...params.header } as {
Authorization: string;
"Application-Version": string;
"Something-Id": string;
},
},
});
}
```This signature allows you to:
- **Omit** the defaulted headers and only pass additional ones (here, `Something-Id`):
```typescript
client.getUsersBulkJobid({header: {"Something-Id": "foobar"}, path: {jobId: "123"}});
```- **Override** all headers, including the defaults:
```typescript
client.getUsersBulkJobid({header: {"Authorization": "foo", "Application-Version": "bar", "Something-Id": "foobar"}, path: {jobId: "123"}});
```If your default headers already include **all** required headers for the endpoint (e.g. `{"Authorization": "Bearer your-token", "Application-Version": "1.0.0", "Something-Id": "123"}` as the second constructor argument), you can omit the `header` parameter entirely:
```typescript
client.getUsersBulkJobid({path: {jobId: "123"}});
```NOTE:
In this context, the "default HTTP headers" are different from the headers in `ClientOptions`.
The headers in `ClientOptions` are always sent implicitly, regardless of the header parameters specified in endpoint methods.
In contrast, the "default HTTP headers" mechanism is intended to reduce the need to repeatedly specify common header parameters
in each endpoint method when their values are already known.## Articles
- [openapi-fetch-gen – Generate TypeScript API client from OpenAPI TypeScript interface definitions created by openapi-typescript - DEV Community](https://dev.to/moznion/openapi-fetch-gen-generate-typescript-api-client-from-openapi-typescript-interface-definitions-kjd)
## For developers
### How to publish this packages
```
$ pnpm ship
```## License
MIT