Sobes.tech
Middle

How did you ensure the typing of API responses? Did you use OpenAPI/Swagger or code generation?

sobes.tech AI

Answer from AI

To ensure type safety of API responses, OpenAPI (Swagger) specifications are often used, which describe the structure of requests and responses. Based on them, you can generate types for the frontend using tools such as openapi-generator or swagger-codegen.

In TypeScript, the popular library openapi-typescript generates types from an OpenAPI specification. This allows for strict typing of data received from the API and helps avoid errors when working with responses.

Example of using openapi-typescript:

openapi-typescript api.yaml --output api-types.ts

In code:

import { paths } from './api-types';

type UserResponse = paths['/users/{id}']['get']['responses']['200']['content']['application/json'];

function fetchUser(id: string): Promise<UserResponse> {
  return fetch(`/users/${id}`).then(res => res.json());
}

Thus, the types automatically match the API specification, increasing reliability and development convenience.

If OpenAPI is not used, types can be manually described or code generation can be used from GraphQL schemas if the API is built on GraphQL.