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.
Example: generated types and RTK Query hooksAdd a generation script to package.json:
{ "scripts": { "generate-types": "dtsgen --out src/api/types/generated-counter-api-types.d.ts specs/prepared-counter-api.yaml" } } The generated declarations include the data models and the types for individual operations:
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; } } } Use them in the API definition:
/// <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. }), }), }); The hooks now carry those types into your components:
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.
Example: a typed fetch function used by useQueryGenerate the declarations:
{ "scripts": { "generate-types": "dtsgen --out src/api/types/generated-api-types.d.ts specs/prepared-openapi.json" } } An excerpt from the generated types:
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; } } } Give the request function a return type from the generated declarations:
/// <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(); } Then use it in a component:
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.
Example: a fetch wrapper with generated response typesThe example uses the same 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 {} } } } The client implementation uses an error/data tuple. 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}`); } } A component can consume the result like this:
const [err, pet] = await apiClient.fetchPetByIdSafe(petId); if (err) { setError(err.message); } else { setData(pet); } The tuple handles HTTP error responses in this wrapper; network failures can still reject the promise. Also, 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
Example: generating a fetch client with OrvalCreate 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', }, }, }); Add a script:
{ "scripts": { "generate-types": "orval" } } Run npm run generate-types. Despite the script's name, this generates both model types and request functions.
For example, the generated pet client includes 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
Example: typed Express controllersGenerate declarations for the service:
{ "scripts": { "generate-types": "dtsgen --out src/services/petstore/generated-api-types.d.ts specs/prepared-petstore.json" } } The example defines a TypedController helper:
export type TypedController<T extends ExpressRouteShape> = ( request: TypedRequest<T>, response: TypedResponse<T>, next: TypedNext<T>, ) => Promise<void> | void; A route shape connects request parameters with the possible response bodies:
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; }; }; The controller then uses those types. Here, 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); Assigning an incompatible object, such as { foo: 'bar' }, to this typed result produces a TypeScript error.
The same pattern works for a POST request body:
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. }; Or for query parameters:
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
Example: generating a model and an endpoint responseTo generate a model, look up its component schema after resolving references:
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)Source:https://dev.to/itwillwork/openapi-for-frontend-developers-types-clients-validation-and-mocks-b69