This is an overview of the OpenAPI Forge documentation and related resources.
Install openapi-forge as a global package.
This gives you access to the openapi-forge CLI tool, which performs a number of functions, including the generation of client APIs. The tool provides high-level usage instructions.
In order to generate a client you need a suitable API specification, this can be supplied as a URL or a local file and can be in JSON or YML format. For this tutorial, we’ll use the Swagger Petstore API:
https://petstore3.swagger.io/api/v3/openapi.json
To create the client API, run the forge command, providing the schema URL, together with a language-specific generator and an output folder:
The above example uses the openapi-forge-typescript which generates a TypeScript client API.
Let’s take a look at the files this has generated:
The generators all create a README.md file which provides language specific usage instructions. Some of the more notable generated files are:
apiPet.ts / apiStore.ts / apiUser.ts - these are the API endpoints, grouped by tags, each file contains a class with methods that relate to the API schema
model.ts - this file contains the models used by the API, for example Pet or Order
configuration.ts - configures the API, for example, allows you to specify the base path or bearer token.
Let’s take a look at a quick example that uses the generated client:
You can run the above code with either ts-node, or a runtime with native TypeScript support such as deno.
The first step is to configure and create a client API instance. In the above example we supply a ‘transport’ implementation, which in this case uses node-fetch. If you want to use a different mechanism, for example Axios or XHR, it is very easy to provide a different implementation. You also need to supply a base path, which indicates where this API is hosted. This example uses the API methods grouped by the ‘pet’ tag, so an instance of ApiPet is required.
To test the API, this example adds a Pet named “Fido” to the Pet Store, then retrieves it via its id, logging the name.
And that’s it, you’ve successfully generated and used your first client library.