DEV Community

Cover image for OpenAPI for Frontend developers: Types, Clients, Validation, and Mocks
itwillwork
itwillwork

Posted on

OpenAPI for Frontend developers: Types, Clients, Validation, and Mocks

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.

Locating an OpenAPI specification in the browser's developer tools

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.ts declarations 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 hooks

Add 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"
  }
}
Enter fullscreen mode Exit fullscreen mode

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;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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.
    }),
  }),
});
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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 useQuery

Generate the declarations:

{
  "scripts": {
    "generate-types": "dtsgen --out src/api/types/generated-api-types.d.ts specs/prepared-openapi.json"
  }
}
Enter fullscreen mode Exit fullscreen mode

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;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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();
}
Enter fullscreen mode Exit fullscreen mode

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),
});
Enter fullscreen mode Exit fullscreen mode

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 types

The 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 {}
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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}`);
  }
}
Enter fullscreen mode Exit fullscreen mode

A component can consume the result like this:

const [err, pet] = await apiClient.fetchPetByIdSafe(petId);
if (err) {
  setError(err.message);
} else {
  setData(pet);
}
Enter fullscreen mode Exit fullscreen mode

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

Full Orval example on GitHub

Example: generating a fetch client with Orval

Create 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',
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

Add a script:

{
  "scripts": {
    "generate-types": "orval"
  }
}
Enter fullscreen mode Exit fullscreen mode

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[];
}
Enter fullscreen mode Exit fullscreen mode

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 controllers

Generate declarations for the service:

{
  "scripts": {
    "generate-types": "dtsgen --out src/services/petstore/generated-api-types.d.ts specs/prepared-petstore.json"
  }
}
Enter fullscreen mode Exit fullscreen mode

The example defines a TypedController helper:

export type TypedController<T extends ExpressRouteShape> = (
  request: TypedRequest<T>,
  response: TypedResponse<T>,
  next: TypedNext<T>,
) => Promise<void> | void;
Enter fullscreen mode Exit fullscreen mode

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;
  };
};
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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.
  };
Enter fullscreen mode Exit fullscreen mode

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.
  };
Enter fullscreen mode Exit fullscreen mode

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:

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,
  }),
);
Enter fullscreen mode Exit fullscreen mode

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:

Full sample-generation example on GitHub

Example: generating a model and an endpoint response

To 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) throw new Error('Component not found');

  const jsonSchema = openapiSchemaToJsonSchema(entitySchema);
  return jsf.generate(jsonSchema) as T;
}

const sample = await createEntitySampleFromOpenApi<
  PetstoreComponents.Schemas.Pet
>('Pet');
Enter fullscreen mode Exit fullscreen mode

To generate an endpoint response, select its method, path, status code, and media type:

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');
Enter fullscreen mode Exit fullscreen mode

The tests illustrate both uses. The same process can supply mock responses in a controller:

const responseMock = await getMockFromOpenApi<
  PetstorePaths.StoreOrder$OrderId.Get.Responses.$200
>('get', '/store/order/{orderId}', '200');

response.result = responseMock;
next();
Enter fullscreen mode Exit fullscreen mode

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.


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"
  }
}
Enter fullscreen mode Exit fullscreen mode

Then run:

npm run mock:api
Enter fullscreen mode Exit fullscreen mode

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 },
    },
  ],
};
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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' },
    },
  }],
};
Enter fullscreen mode Exit fullscreen mode

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' },
    },
  }],
};
Enter fullscreen mode Exit fullscreen mode

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' },
    },
  }],
};
Enter fullscreen mode Exit fullscreen mode

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/' } },
  }],
};
Enter fullscreen mode Exit fullscreen mode

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' },
  ],
};
Enter fullscreen mode Exit fullscreen mode

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' },
  ],
};
Enter fullscreen mode Exit fullscreen mode

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' } },
    },
  ],
};
Enter fullscreen mode Exit fullscreen mode

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(?:\/|$)/] },
  }],
};
Enter fullscreen mode Exit fullscreen mode

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' },
    },
  }],
};
Enter fullscreen mode Exit fullscreen mode

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' } },
      },
    },
  }],
};
Enter fullscreen mode Exit fullscreen mode

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-deprecated excludes deprecated elements from the derived specification, helping surface migration work when you regenerate consumers.
  • remove-unused-components cleans up components that are no longer referenced, for example after filtering endpoints.
  • merge-openapi-spec brings 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)