Type a function based on OpenApi — Learn TypeScript training

In this tutorial I suggest you discover the @grafikart/o2ts library which will allow you to convert an OpenAPI 3+ definition file to TypeScript type.

The goal

The goal is to create a function that will call the API and return the results to us. The signature will look like this fetchAPI(endpoint, options) and we want Typescript to check the parameters:

  • endpoint must correspond to an entry point of our API.
  • options.method will contain the HTTP method to use, and will match the given endpoint.
  • options.query should be an object that matches what the API accepts for query parameters.
  • options.urlParams will allow to add parameters in the URL (if the endpoint is /post/{id} for example, we would expect that id is required)
  • options.body must be an object if the request expects a body in application/json.
  • The response must automatically be typed according to the parameters received.

The solution

In a first iteration I had tried to use the openapi-typescript library but it translates the OpenAPI file too literally and the extraction of information requires complex type utilities which makes the types difficult to debug.

That’s why I decided to create my own tool, @grafikart/o2ts, which will directly extract important information from the OpenAPI file with usable types. The library will generate some utility types that you can use in your functions.

  • APIPathswill represent all possible endpoints
  • APIMethods<Path>will represent all possible methods for a given endpoint
  • APIRequests<Path>will return all possible requests for the endpoint
  • APIRequest<Path, Method>will return the type of request to make for this endpoint
  • APIResult<Path, Method>will return the type of the response from the server
  • APISchema<Schema>provides access to the schemas defined in the OpenAPI file