Skip to content

Commit fb1f8b8

Browse files
committed
fix: improve documentation
1 parent aacc1fe commit fb1f8b8

File tree

1 file changed

+172
-46
lines changed

1 file changed

+172
-46
lines changed

README.md

Lines changed: 172 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,56 @@
11
# OpenAPI Typescript Client Generator
22

3-
Generates OpenAPI client for TypeScript. Extremely configurable.
3+
A powerful, highly customizable TypeScript client generator for OpenAPI specifications. Build type-safe API clients for any environment with unprecedented control over generated code.
44

55
## Features
66

7-
1. Generates TypeScript models for all the schemas in the OpenAPI document in a form of interfaces and type aliases.
8-
2. Generates TypeScript services for all the operations in the OpenAPI document.
9-
3. Generates a client class that combines all the services.
10-
4. Uses `fetch` API for making HTTP requests by default, but can be configured to use any other HTTP client.
11-
5. May generate validation for the API responses if configured.
7+
- **Fully-typed**: Generates TypeScript models for all schemas and operations
8+
- **Environment-agnostic**: Generated clients work everywhere - browsers, Node.js, Sandbox environments, and more
9+
- **Validation support**: Optional runtime validation for requests and responses
10+
- **Highly customizable**: Control everything from naming conventions to file structure
11+
- **Production-ready**: Used to build enterprise-grade API clients for Atlassian products
12+
- **Flexible schema loading**: Load schemas from YAML or JSON, locally or remotely
13+
- **Modern specification support**: Full support for OpenAPI 3.0 and 3.1
14+
15+
## Real-world Examples
16+
17+
Built by the team behind production API clients:
18+
- `@resolution/jira-api-client` - Fully-typed Jira API client
19+
- `@resolution/confluence-api-client` - Fully-typed Confluence API client
20+
21+
These clients support multiple environments (Atlassian Connect Server/Client, Atlassian Forge Backend/Frontend) from a single codebase - showcasing the flexibility of this generator.
22+
23+
## Comparison with Alternatives
24+
25+
| Feature | api-typescript-generator | openapi-typescript | openapi-ts + openapi-fetch |
26+
|-----------------------------|--------------------------|--------------------|--------------------------------------------|
27+
| Type Generation ||||
28+
| Client Generation ||| ❌ (`openapi-fetch` can use generated types) |
29+
| Customizable File Structure ||| N/A |
30+
| Custom Naming Conventions ||||
31+
| JSDoc Generation ||||
32+
| JSDoc Customization ||||
33+
| Validation | ✅ (configurable) |||
34+
| Environment-agnostic ||||
35+
| No runtime dependencies ||||
1236

1337
## Setup
1438

15-
Install using npm
39+
Install using npm:
1640

1741
```shell
1842
npm add --save-dev api-typescript-generator
1943
```
2044

21-
Or using yarn
45+
Or using yarn:
2246

2347
```shell
2448
yarn add --dev api-typescript-generator
2549
```
2650

27-
## Configuring
51+
## Configuration
2852

29-
Create a `api-typescript-generator.config.ts` file in the root of your project.
53+
Create a `api-typescript-generator.config.ts` file in your project root:
3054

3155
```ts
3256
import path from 'path';
@@ -60,13 +84,11 @@ const configuration: ApiTypescriptGeneratorConfig = {
6084
export default configuration;
6185
```
6286

63-
Add the following script to your `package.json`:
87+
Add a script to your `package.json`:
6488

65-
```js
89+
```json
6690
{
67-
// ...
6891
"scripts": {
69-
// ...
7092
"openapi-codegen": "api-typescript-generator generate api-typescript-generator.config.ts"
7193
}
7294
}
@@ -78,61 +100,165 @@ Run the script:
78100
npm run openapi-codegen
79101
```
80102

81-
Or using yarn:
103+
## Basic Usage
82104

83-
```shell
84-
yarn openapi-codegen
105+
```ts
106+
import {PetStoreApiClient} from './petstore-api-client';
107+
108+
const client = new PetStoreApiClient();
109+
110+
// Type-safe API calls
111+
async function getPets() {
112+
const pets = await client.pet.findByStatus({status: 'available'});
113+
console.log(pets); // Fully typed response
114+
}
115+
116+
// Error handling with typed errors
117+
try {
118+
await client.pet.addPet({/* pet data */});
119+
} catch (error) {
120+
if (error instanceof client.HttpClientError) {
121+
console.error('API Error:', error.status, error.message);
122+
}
123+
}
85124
```
86125

87-
By default it generates:
126+
## Advanced Usage
88127

89-
1. Models for all the schemas in the OpenAPI document. Stored at `models` directory by default.
90-
2. Services for all the operations in the OpenAPI document. Stored at `services` directory by default.
91-
3. A client class that combines all the services. Stored at the root of the output directory by default.
92-
4. Core classes for handling HTTP requests and responses. Stored at `core` directory by default.
128+
### Validation with Zod
93129

94-
## Usage
130+
Why you might want to enable validation:
95131

96-
The generated client can be used as follows:
132+
- OpenAPI specifications can be incomplete or incorrect.
133+
- Runtime validation can catch issues that static type checking cannot.
134+
- Validation can help ensure that your API client behaves as expected.
97135

98136
```ts
99-
import {PetStoreApiClient} from './petstore-api-client';
100-
101-
async function testApiClient() {
102-
const apiClient = new PetStoreApiClient();
103-
console.log(await client.store.getInventory());
137+
// In config:
138+
validation: {
139+
library: 'zod'
104140
}
105141

106-
testApiClient().catch(console.error);
142+
// Option 1. Throw validation errors
143+
const client = new PetStoreApiClient();
144+
const result = await client.pet.getPetById({petId: '123'});
145+
// In case of validation error, an exception will be thrown.
146+
147+
// Option 2. Handle validation errors separately (i.e. send to Sentry)
148+
const client = new PetStoreApiClient({
149+
handleValidationError(error) {
150+
Sentry.captureException(error);
151+
}
152+
});
153+
const result = await client.pet.getPetById({petId: '123'});
154+
// In case of validation error, the error will be sent to Sentry, and the execution will continue.
107155
```
108156

109-
## What is configurable?
157+
### Custom HTTP Client
110158

111-
1. Validation of the API responses. See [validation](docs/interfaces/openapi_client.OpenApiClientGeneratorConfig.md#validation).
112-
2. Default base URL for the API. See [client.baseUrl](docs/interfaces/openapi_client.OpenApiClientGeneratorConfigClient.md#baseUrl).
113-
3. Leading and trailing comments for the files. See [comments](docs/interfaces/openapi_client.OpenApiClientGeneratorConfigComments.md).
114-
4. File naming conventions. I.e. [models.filenameFormat](docs/interfaces/openapi_client.OpenApiClientGeneratorConfigModels.md#filenameFormat).
115-
5. Output directory structure. I.e. [models.relativeDirPath](docs/interfaces/openapi_client.OpenApiClientGeneratorConfigModels.md#relativeDirPath).
116-
6. JSDoc generation. I.e. [models.generateJsDoc](docs/interfaces/openapi_client.OpenApiClientGeneratorConfigModels.md#generateJsDoc).
117-
7. Many more. See the documentation below.
159+
```ts
160+
const client = new PetStoreApiClient({
161+
fetch: customFetchImplementation,
162+
baseUrl: 'https://custom-petstore.example.com',
163+
middlewares: [
164+
request => {
165+
request.headers['X-Custom-Header'] = 'value';
166+
return request;
167+
}
168+
]
169+
});
170+
```
171+
172+
### Retry Logic
173+
174+
You can implement custom retry logic for your API client. This is useful for handling transient errors or rate limiting.
175+
176+
```ts
177+
const client = new PetStoreApiClient({
178+
shouldRetryOnError: (error, attempt) => {
179+
if (error.status >= 500 && attempt < 3) {
180+
return new Promise((resolve) => {
181+
setTimeout(() => resolve(true), 100 * attempt);
182+
});
183+
}
184+
return false;
185+
}
186+
});
187+
```
188+
189+
### Deprecated API Operations
190+
191+
In case if an operation is marked as deprecated in OpenAPI spec, the generator will add a `@deprecated` tag to the generated method.
192+
When calling a deprecated method, a warning will be logged to the console.
193+
You can customize the logging behavior by providing a custom `logDeprecationWarning` function in the client configuration.
194+
195+
```ts
196+
const client = new PetStoreApiClient({
197+
logDeprecationWarning: ({
198+
operationName,
199+
path,
200+
method
201+
}) => {
202+
Sentry.captureMessage(`Deprecated API call: ${operationName} (${method.toUpperCase()} ${path})`);
203+
}
204+
});
205+
```
206+
207+
## Customization Options
208+
209+
The generator offers unmatched customization:
210+
211+
1. **File Structure Control**
212+
- Custom directory structure
213+
- Configurable file naming patterns
214+
- Grouped or flat output
215+
216+
2. **Naming Conventions**
217+
- Model/interface naming patterns
218+
- Property naming transformation
219+
- Service method naming
220+
221+
3. **Documentation**
222+
- JSDoc generation with wordwrap control
223+
- Custom section ordering
224+
- Description formatting
225+
- Custom tags and annotations
226+
227+
4. **Client Features**
228+
- Response validation
229+
- Error handling strategies
230+
- Binary data processing
231+
- Custom fetch implementation
232+
- Custom request/response interceptors
233+
- Custom retry logic
118234

119235
## Documentation
120236

121-
The most important interface for now would be the [OpenApiClientGeneratorConfig](docs/interfaces/openapi_client.OpenApiClientGeneratorConfig.md) interface. It contains all the configuration options for the OpenAPI Client Generator.
237+
For full configuration options, see:
238+
239+
- [OpenApiClientGeneratorConfig](docs/interfaces/openapi_client.OpenApiClientGeneratorConfig.md) - Main configuration interface
240+
- [Models Configuration](docs/interfaces/openapi_client.OpenApiClientGeneratorConfigModels.md) - Model generation options
241+
- [Services Configuration](docs/interfaces/openapi_client.OpenApiClientGeneratorConfigServices.md) - Service generation options
242+
- [Validation Configuration](docs/interfaces/openapi_client.OpenApiClientGeneratorConfigValidation.md) - Validation options
122243

123-
Types are exported as part of three modules, depending on the area of application:
244+
## Modules
124245

125-
1. [`api-typescript-generator`](docs/modules/index.md) - The main module that exports the common API Generator Configuration types.
126-
2. [`api-typescript-generator/openapi-client`](docs/modules/openapi_client.md) - The module that exports the OpenAPI Client Generator Configuration types.
127-
3. [`api-typescript-generator/openapi`](docs/modules/openapi.md) - The module that exports the OpenAPI Document types.
246+
Types are exported from three modules:
128247

129-
At the moment only types are exported to be used with CLI. Callable API is planned for the future.
248+
1. [`api-typescript-generator`](docs/modules/index.md) - Common API Generator types
249+
2. [`api-typescript-generator/openapi-client`](docs/modules/openapi_client.md) - OpenAPI Client types
250+
3. [`api-typescript-generator/openapi`](docs/modules/openapi.md) - OpenAPI Document types
130251

131-
## Collaborators
252+
## Contributors
132253

133-
* [Mikhail Davydov](https://github.com/azproduction)
254+
* [Marat Dulin](https://github.com/mdevils)
255+
* [Mikhail Davydov](https://github.com/azproduction)
134256

135257
## References
136258

137259
1. [OpenAPI Specification](https://swagger.io/specification/)
138260
2. [JSON Schema](https://json-schema.org/)
261+
262+
## License
263+
264+
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.

0 commit comments

Comments
 (0)