OpenAPI can do much more than power a Swagger UI page. The same specification can help you:
- Generate TypeScript types for RTK Query, TanStack Query, and native
fetch. - Generate API clients instead of writing request functions by hand.
- Share request and response types with an Express backend for frontend (BFF).
- Validate requests and responses at runtime.
- Generate sample data for development and integration tests.
- Run a mock API while the backend is still being built.
But all of these workflows depend on the specification being usable. What happens when it contains typos, omits a field, or uses a structure your generator cannot handle?
I'll walk through the six workflows first, then show how to keep specification fixes reproducible with openapi-modifier.
The code blocks below focus on the relevant pieces; each example links to the full project, including setup and supporting utilities.
First, find the specification
OpenAPI is a standard for describing HTTP APIs in a machine-readable YAML or JSON document. Swagger UI and ReDoc turn that document into browsable API documentation.
If you only have a documentation URL, open your browser's developer tools, switch to the Network tab, and reload the page. Look for the request that loads the specification. It may be a .json, .yaml, or .yml file, although the URL does not have to use one of those extensions. Inspect the response for an openapi version field, or swagger for an older Swagger 2.0 document.
1. Generate TypeScript types
Generating types from an API contract saves you from maintaining a second set of interfaces by hand. This is especially useful when an API changes frequently: regenerating the types makes many incompatible changes visible during compilation.
Tools covered by this workflow include:
- openapi-typescript, which generates types without generating runtime request code.
-
dtsgenerator, which generates
.d.tsdeclarations and is used in the examples below. - OpenAPI Generator, which also supports client and server generation.
Generated types describe the contract at compile time. They do not check whether an actual HTTP response matches that contract. Runtime validation is a separate step, covered later.
RTK Query
Full RTK Query example on GitHub
Generate declarations, then use the generated request and response types as the generic parameters of your RTK Query endpoints.
Add a generation script to The generated declarations include the data models and the types for individual operations: Use them in the API definition: The hooks now carry those types into your components:Example: generated types and RTK Query hooks
package.json:
{
"scripts": {
"generate-types": "dtsgen --out src/api/types/generated-counter-api-types.d.ts specs/prepared-counter-api.yaml"
}
}
declare namespace Components {
namespace Schemas {
export interface CounterResponse {
value: number; // int32
}
export interface CounterRequest {
value: number; // int32
}
}
}
declare namespace Paths {
namespace GetCounter {
export interface QueryParameters {
version?: string;
}
namespace Responses {
export type $200 = Components.Schemas.CounterResponse;
}
}
namespace SaveCounter {
export type RequestBody = Components.Schemas.CounterRequest;
namespace Responses {
export type $200 = Components.Schemas.CounterResponse;
}
}
}
/// <reference path="../../api/types/generated-counter-api-types.d.ts" />
export const counterApi = createApi({
// Other API options omitted.
endpoints: (builder) => ({
getCounter: builder.query<
Paths.GetCounter.Responses.$200,
Paths.GetCounter.QueryParameters
>({
// Request configuration omitted.
}),
saveCounter: builder.mutation<
Paths.SaveCounter.Responses.$200,
Paths.SaveCounter.RequestBody
>({
// Request configuration omitted.
}),
}),
});
const { data, isLoading, error } = useGetCounterQuery({ version });
const [saveCounter] = useSaveCounterMutation();
// When present, data has type Paths.GetCounter.Responses.$200.
// saveCounter accepts Paths.SaveCounter.RequestBody.
TanStack Query (React Query)
Full TanStack Query example on GitHub
With TanStack Query, a typed request function is enough for the query result to be inferred.
Generate the declarations: An excerpt from the generated types: Give the request function a return type from the generated declarations: Then use it in a component:Example: a typed fetch function used by useQuery
{
"scripts": {
"generate-types": "dtsgen --out src/api/types/generated-api-types.d.ts specs/prepared-openapi.json"
}
}
declare namespace Components {
namespace Schemas {
export interface Pet {
id?: number; // int64
name: string;
photoUrls: string[];
status?: "available" | "pending" | "sold";
category?: Category;
tags?: Tag[];
}
// Category and Tag declarations omitted.
}
}
declare namespace Paths {
namespace GetPetById {
export interface PathParameters {
petId: number; // int64
}
namespace Responses {
export type $200 = Components.Schemas.Pet;
}
}
}
/// <reference path="./types/generated-api-types.d.ts" />
export async function fetchPetById(
petId: number,
): Promise<Paths.GetPetById.Responses.$200> {
const res = await fetch(`http://localhost:4010/api/v3/pet/${petId}`);
if (!res.ok) {
throw new Error('Pet is not found');
}
return res.json();
}
import { useQuery } from '@tanstack/react-query';
import { fetchPetById } from './api/fetchPetById';
// Inside the component:
const { isPending, error, data } = useQuery({
queryKey: ['pet', petId],
queryFn: () => fetchPetById(petId),
});
Native fetch
Full native fetch example on GitHub
You can use the same approach without a query library: generate types and reference them in a small API wrapper.
The example uses the same The client implementation uses an error/data tuple. A component can consume the result like this: The tuple handles HTTP error responses in this wrapper; network failures can still reject the promise. Also, Example: a fetch wrapper with generated response types
dtsgen command as the TanStack Query project. Its generated operation types include both success and error responses:
declare namespace Paths {
namespace GetPetById {
export interface PathParameters {
petId: number;
}
namespace Responses {
export type $200 = Components.Schemas.Pet;
export interface $404 {}
}
}
}
ApiResult and ApiError are helpers defined in that project:
/// <reference path="./types/generated-api-types.d.ts" />
export class ApiClient {
private baseUrl: string;
constructor(baseUrl: string) {
this.baseUrl = baseUrl;
}
async get<T, E = unknown>(
path: string,
options?: RequestInit,
): Promise<ApiResult<T, E>> {
const url = `${this.baseUrl}${path}`;
const res = await fetch(url, { ...options, method: 'GET' });
if (!res.ok) {
const error = new ApiError(res.statusText, res.status);
return [error, null];
}
const data = (await res.json()) as T;
return [null, data];
}
async fetchPetByIdSafe(
petId: number,
): Promise<ApiResult<
Paths.GetPetById.Responses.$200,
Paths.GetPetById.Responses.$404
>> {
return this.get<
Paths.GetPetById.Responses.$200,
Paths.GetPetById.Responses.$404
>(`/api/v3/pet/${petId}`);
}
}
const [err, pet] = await apiClient.fetchPetByIdSafe(petId);
if (err) {
setError(err.message);
} else {
setData(pet);
}
as T is a type assertion, not a runtime check of the JSON payload.
2. Generate API clients
Generating types still leaves you writing request functions. Client generation takes the next step: it produces those functions too, including the code that builds URLs and passes parameters.
Some options from the ecosystem:
A related option is openapi-fetch: it uses generated types with a runtime fetch client, rather than generating a separate function for each operation.
An Orval example
Create Add a script: Run For example, the generated pet client includes Example: generating a fetch client with Orval
orval.config.ts:
import { defineConfig } from 'orval';
export default defineConfig({
api: {
input: {
target: './specs/prepared-openapi.json',
},
output: {
target: './src/api/generated/api.ts',
client: 'fetch',
mode: 'tags',
baseUrl: 'http://localhost:4010',
},
},
});
{
"scripts": {
"generate-types": "orval"
}
}
npm run generate-types. Despite the script's name, this generates both model types and request functions.getPetById, while the schema file contains models such as:
export interface Pet {
category?: Category;
id?: number;
name: string;
photoUrls: string[];
/** pet status in the store */
status?: PetStatus;
tags?: Tag[];
}
3. Type an Express BFF with the same contract
A backend for frontend often adapts upstream APIs to the needs of a UI. Generated types let the BFF reuse the upstream request and response models rather than maintaining another handwritten copy.
This catches incompatible assignments during compilation and improves autocomplete. It does not parse incoming values or validate them at runtime: for example, a route parameter arriving as text still needs to be handled appropriately.
Full typed Express proxy example on GitHub
Generate declarations for the service: The example defines a TypedController helper: A route shape connects request parameters with the possible response bodies: The controller then uses those types. Here, Assigning an incompatible object, such as The same pattern works for a POST request body: Or for query parameters:Example: typed Express controllers
{
"scripts": {
"generate-types": "dtsgen --out src/services/petstore/generated-api-types.d.ts specs/prepared-petstore.json"
}
}
export type TypedController<T extends ExpressRouteShape> = (
request: TypedRequest<T>,
response: TypedResponse<T>,
next: TypedNext<T>,
) => Promise<void> | void;
type GetOrderByIdRoute = {
request: {
params: {
orderId: PetstorePaths.StoreOrder$OrderId.Get.Parameters.OrderId;
};
};
responses: {
success: PetstorePaths.StoreOrder$OrderId.Get.Responses.$200;
error:
| PetstorePaths.StoreOrder$OrderId.Get.Responses.$400
| PetstorePaths.StoreOrder$OrderId.Get.Responses.$404;
};
};
response.result is part of the example project's response-handling convention, not a built-in Express property:
const getOrderByIdRouteTypedController: TypedController<GetOrderByIdRoute> =
async (request, response, next) => {
const responseMock = await getMockFromOpenApi<
PetstorePaths.StoreOrder$OrderId.Get.Responses.$200
>('get', '/store/order/{orderId}', '200');
response.result = responseMock;
next();
};
app.get('/store/order/:orderId', getOrderByIdRouteTypedController);
{ foo: 'bar' }, to this typed result produces a TypeScript error.
type PlaceOrderRoute = {
request: {
body: PetstorePaths.StoreOrder.Post.RequestBody;
};
responses: {
success: PetstorePaths.StoreOrder.Post.Responses.$200;
error:
| PetstorePaths.StoreOrder.Post.Responses.$400
| PetstorePaths.StoreOrder.Post.Responses.$422;
};
};
const placeOrderRouteTypedController: TypedController<PlaceOrderRoute> =
async (request, response, next) => {
const order = request.body;
// order uses the generated request body type.
// Controller implementation omitted.
};
type LoginUserRoute = {
request: {
query: PetstorePaths.UserLogin.Get.QueryParameters;
};
responses: {
success: PetstorePaths.UserLogin.Get.Responses.$200;
error: PetstorePaths.UserLogin.Get.Responses.$400;
};
};
const loginUserRouteTypedController: TypedController<LoginUserRoute> =
async (request, response, next) => {
const username = request.query.username; // string | undefined
const password = request.query.password; // string | undefined
// Controller implementation omitted.
};
4. Validate Express requests and responses
Compile-time types help you write code against a contract. Runtime validation checks the data actually crossing the HTTP boundary.
An OpenAPI document can supply the schemas for that validation, so you do not have to describe the same request twice.
Libraries for this include:
- express-openapi-validator, for Express middleware.
- openapi-request-validator, for request validation.
- openapi-response-validator, for response validation.
Full Express validation example on GitHub
The core configuration passes the specification to the middleware:
app.use(
OpenApiValidator.middleware({
apiSpec: openApiSpec,
validateRequests: true,
validateResponses: true,
}),
);
See the full middleware setup for its placement in the Express application.
5. Generate sample data for development and tests
A specification also contains enough structure to generate sample models and response bodies.
You can use openapi-sampler, or combine a schema converter with json-schema-faker.
The following example uses three tools:
-
@apidevtools/json-schema-ref-parser to resolve
$refreferences. - @openapi-contrib/openapi-schema-to-json-schema to convert a schema to JSON Schema.
- json-schema-faker to generate sample data.
Full sample-generation example on GitHub
To generate a model, look up its component schema after resolving references: To generate an endpoint response, select its method, path, status code, and media type: The tests illustrate both uses. The same process can supply mock responses in a controller: The generic argument gives callers a TypeScript type; it does not verify that the selected schema corresponds to that type. Likewise, a truthiness assertion only proves that a value was generated. Use schema validation when a test needs to prove contract conformance, and explicit fixtures for business scenarios that require particular values.Example: generating a model and an endpoint response
async function createEntitySampleFromOpenApi<T>(
entityName: string,
): Promise<T> {
const specPath = path.join(__dirname, '../specs/petstore.json');
const spec = JSON.parse(fs.readFileSync(specPath, 'utf-8'));
const dereferenced: any = await RefParser.dereference(spec);
const entitySchema = dereferenced.components.schemas[entityName];
if (!entitySchema) throw new Error('Component not found');
const jsonSchema = openapiSchemaToJsonSchema(entitySchema);
return jsf.generate(jsonSchema) as T;
}
const sample = await createEntitySampleFromOpenApi<
PetstoreComponents.Schemas.Pet
>('Pet');
async function createEndpointResponseSampleFromOpenApi<T>(
method: string,
endpointPath: string,
statusCode: string,
): Promise<T> {
const specPath = path.join(__dirname, '../specs/petstore.json');
const spec = JSON.parse(fs.readFileSync(specPath, 'utf-8'));
const dereferenced: any = await RefParser.dereference(spec);
const pathItem = dereferenced.paths[endpointPath];
if (!pathItem) throw new Error('Path not found');
const op = pathItem[method.toLowerCase()];
if (!op) throw new Error('Method not found');
const resp = op.responses && op.responses[statusCode];
if (!resp) throw new Error('Status code not found');
const content = resp.content && resp.content['application/json'];
if (!content || !content.schema) {
throw new Error('Response schema not found');
}
const jsonSchema = openapiSchemaToJsonSchema(content.schema);
return jsf.generate(jsonSchema) as T;
}
const sampleResponse = await createEndpointResponseSampleFromOpenApi<
PetstorePaths.Pet$PetId.Get.Responses.$200
>('get', '/pet/{petId}', '200');
const responseMock = await getMockFromOpenApi<
PetstorePaths.StoreOrder$OrderId.Get.Responses.$200
>('get', '/store/order/{orderId}', '200');
response.result = responseMock;
next();
6. Run a mock server
Sometimes the frontend needs an HTTP API before the backend implementation is ready. A mock server can read an OpenAPI document and respond to requests using the schemas and examples it contains.
Prism is one option. Another approach is to generate handlers with msw-auto-mock for use with MSW. json-server can also be useful for mock APIs, but it starts from a JSON data file rather than consuming OpenAPI directly.
Full mock-server example on GitHub
With Prism installed in the example project, add this script:
{
"scripts": {
"mock:api": "prism mock specs/prepared-openapi.json -h 0.0.0.0 -p 4010 --cors"
}
}
Then run:
npm run mock:api
The mock API is available at http://localhost:4010, with CORS enabled for the frontend. Its behavior comes from the specification, so it is useful for integration work but does not reproduce backend business logic.
When the specification gets in the way
These workflows all depend on the same input. If that input is wrong or incompatible with a tool, the automation becomes much less useful.
Common problems include:
- A typo in a manually maintained schema.
- A valid schema construct that a particular generator does not handle well.
- A specification generated from backend code that does not fit the frontend toolchain.
- A new field or endpoint that has been agreed on but is not yet in the published contract.
Editing the downloaded file by hand may unblock you once. The next update overwrites those fixes, and someone has to remember what changed and why.
A more repeatable workflow has two parts: validate the specification, then apply explicit preparation rules where needed.
Validate the specification
Redocly CLI and Spectral can help detect specification issues and enforce rules.
Validation helps identify structural problems. It does not prove that the backend behaves as documented, and linting one version of a document is not the same as checking whether an API change is backward compatible.
Prepare the specification
Redocly supports document transformations through decorators, including custom decorators written in JavaScript.
Another option is openapi-modifier. It provides rules that you compose into a pipeline: merge a feature specification, patch a schema, normalize content types, filter endpoints, and remove components that are no longer used.
Here is an example configuration:
module.exports = {
input: './openapi.yaml',
output: './openapi.mod.yaml',
logger: { verbose: true },
pipeline: [
// JIRA-232: include endpoints for the new feature.
{
rule: 'merge-openapi-spec',
config: { path: 'docs/feature-JIRA-232.yaml' },
},
// JIRA-8752: fix the ID type without replacing the rest of Pet.
{
rule: 'patch-component-schema',
config: {
descriptor: 'Pet.id',
patchMethod: 'merge',
schemaDiff: { type: 'string', format: 'uuid' },
},
},
// Normalize media types before patching the JSON response.
{
rule: 'change-content-type',
config: { map: { '*/*': 'application/json' } },
},
{
rule: 'filter-by-content-type',
config: { disabled: ['multipart/form-data'] },
},
// Fix status values in an inline array response without a $ref.
{
rule: 'patch-endpoint-response-schema',
config: {
endpointDescriptor: 'GET /v1/pets',
code: '200',
contentType: 'application/json',
correction: '[].status',
patchMethod: 'merge',
schemaDiff: { enum: ['active', 'archived'] },
},
},
// Apply compatibility adjustments needed by this generator setup.
{ rule: 'remove-operation-id' },
{ rule: 'remove-min-items' },
// Exclude deprecated and internal endpoints from the derived spec.
{
rule: 'remove-deprecated',
config: { showDeprecatedDescriptions: true },
},
{
rule: 'filter-endpoints',
config: { disabledPathRegExp: [/^\/internal(?:\/|$)/] },
},
// Clean up components left unused after filtering.
{
rule: 'remove-unused-components',
config: { printDeletedComponents: true },
},
],
};
Rules run in order. In this example, media types are normalized before a JSON response is patched, and unused components are removed after endpoints are filtered.
Treat this as a menu of transformations, not a default configuration to apply to every API. Removing constraints or operations changes the derived contract. A document prepared for a particular code generator may therefore be unsuitable as the input for runtime validation.
Recipes for common specification problems
The following are independent configurations. Model names, fields, and paths are illustrative; replace them with the ones in your specification.
Save a configuration as openapi-modifier.config.js and run:
npx openapi-modifier --input openapi.yaml --output prepared-openapi.yaml --config openapi-modifier.config.js
Fix an invalid type name
If a field uses int where the schema requires integer, patch that field:
module.exports = {
pipeline: [{
rule: 'patch-component-schema',
config: {
descriptor: 'Pet.id',
patchMethod: 'merge',
schemaDiff: { type: 'integer' },
},
}],
};
Correct a date format
If a field uses datetime but is intended to use the standard date-time format:
module.exports = {
pipeline: [{
rule: 'patch-component-schema',
config: {
descriptor: 'Pet.createdAt',
patchMethod: 'merge',
schemaDiff: { type: 'string', format: 'date-time' },
},
}],
};
Make an object type explicit
If a model is intended to be an object but omits type: object, and your generator needs it explicitly:
module.exports = {
pipeline: [{
rule: 'patch-component-schema',
config: {
descriptor: 'Pet',
patchMethod: 'merge',
schemaDiff: { type: 'object' },
},
}],
};
Change endpoint path prefixes
If a proxy exposes the API under a different prefix:
module.exports = {
pipeline: [{
rule: 'change-endpoints-basepath',
// /pets becomes /api/v1/pets. This changes paths keys, not servers.
config: { map: { '/': '/api/v1/' } },
}],
};
Remove array size constraints for a generator
If minItems or maxItems causes a compatibility problem in your generator:
module.exports = {
pipeline: [
{ rule: 'remove-min-items' },
{ rule: 'remove-max-items' },
],
};
These constraints may still matter to the API. Removing them from a generation input does not remove the backend's requirements.
Remove operation IDs
If existing operation IDs interfere with your generator's naming strategy:
module.exports = {
pipeline: [
{ rule: 'remove-operation-id' },
],
};
Regeneration may change exported names, so review the generated diff and update consumers as needed.
Filter or normalize media types
To exclude XML and replace a wildcard media type with JSON:
module.exports = {
pipeline: [
{
rule: 'filter-by-content-type',
config: { disabled: ['application/xml'] },
},
{
rule: 'change-content-type',
config: { map: { '*/*': 'application/json' } },
},
],
};
Use the wildcard replacement only when JSON is the actual format you intend to describe.
Exclude private endpoints from a frontend specification
If the frontend does not need /private endpoints:
module.exports = {
pipeline: [{
rule: 'filter-endpoints',
config: { disabledPathRegExp: [/^\/private(?:\/|$)/] },
}],
};
This removes them from the derived document. It does not restrict access to the real endpoints.
Prepare for a parameter removal
If a query parameter is about to disappear, remove it from the prepared specification and regenerate the types or client:
module.exports = {
pipeline: [{
rule: 'remove-parameter',
config: {
endpointDescriptor: 'GET /pets',
parameterDescriptor: { name: 'version', in: 'query' },
},
}],
};
Type errors in affected callers can help you find usages that need to be migrated before the backend change lands.
Add an agreed field before the upstream specification is updated
If frontend work needs to start on a field that has already been agreed on:
module.exports = {
pipeline: [{
rule: 'patch-component-schema',
config: {
descriptor: 'Pet',
patchMethod: 'deepmerge',
schemaDiff: {
// Add an optional color field while preserving existing properties.
properties: { color: { type: 'string' } },
},
},
}],
};
This makes the field available to generated types and mocks. It does not make it available on the live backend.
Keep the reasons alongside the fixes
Three other rules are useful as the specification evolves:
-
remove-deprecatedexcludes deprecated elements from the derived specification, helping surface migration work when you regenerate consumers. -
remove-unused-componentscleans up components that are no longer referenced, for example after filtering endpoints. -
merge-openapi-specbrings in a separate feature specification before it is merged into the main document.
The practical benefit is being able to repeat the same preparation after every upstream update. Keep each fix small and add a comment explaining why it exists, ideally with a link or reference to the relevant issue. You can use a rule more than once to keep unrelated fixes separate.
That gives the team a reviewable record of the differences between the upstream contract and the document its tools consume. Once an upstream issue is fixed, the corresponding workaround can be reviewed and removed.
The example projects show how these pieces fit together: prepare a specification, generate types or clients, and use the contract for validation and mocks where appropriate.

Top comments (0)