If you have a look at my previous articles here at dev.to you would see that I enjoy automating the little things. Especially the boring, tedious stuff that can lead to errors.
In this article we will be looking on how you can generate code from the OpenAPI spec so that your application is always in sync with the API.
There are many reasons why you may want to do that, but the main one is that your backend and frontend will adhere to the same schema.
The article covers mainly frontend applications based on React, Vue or even Angular. However the concept is quite generic and it can be used in backend also regardless using PHP, NodeJS or something else.
There are a couple of option to achieve this. Before getting started make sure to have a valid OpenAPI spec on your hands.
The first and perhaps the most popular option is to use the OpenAPI generator.
For each generator, there are different options available that you can use to adjust the generated code to your needs. For example, you can control things like the naming convention for enums and parameters, add a prefix and many more.
Here is how you can generate the code for a Typescript project with Axios, by using Docker:
docker run --rm \ -v $PWD:/local openapitools/openapi-generator-cli generate \ -i /api-specy.aml \ -g typescript-axios \ -o /output
OpenAPI Generator is a great tool. However, someone might find that it does not fit very well to the NodeJS ecosystem. All of a sudden you have a Java dependency that you need somehow to manage.
This package can be used to consume the API directly without pre-generating the services. If necessary though, you can generate typescript type files (.d.ts) .
This package generates an Angular module which includes services, configuration and the schema models. It's quite powerful and there are some handy options to adjust the generated code.
While it's possible to commit the generated code, I usually avoid that. I prefer instead to commit only the OpenAPI spec file and then generate the necessary code right before the build.
This helps to ensure that the generated code is intact and it has not modified manually. It usually takes a few seconds even for quite large specs so time shouldn't be a problem.
To do that, you can modify
npm run and
npm build to always execute the code conversion before actually building the app.
If you would like to commit the code anyway, you could have Github action that runs, generates the code and then create a PR with all the changes made.
I hope you enjoyed the article and it's something that you can use to save you some time!