Reuse models and autogenerate http-clients

Http-clients and models
Imagine you create a web application with a front end and a backend with many entities to handle and manage. You might start with the backend and create your repositories, services, and controllers. After that, you create a front end and rewrite the same models and DTOs as you have written in the backend, as well as an HTTP client to interact with the API. This is usually a lengthy and error-prone process. I’ll show you how to generate these things automatically.
Autogenerate
The first thing you must do is to enable or integrate an openapi service in your backend, aka “swagger”. In java springboot
, this is done by importing the org.springdoc:springdoc-openapi-starter-webmvc-ui
dependency. Afterward, you can implement an openapi-api-generator like hey-api/openapi-ts github
in your frontend project.
The next step is to call the following command, which will automatically generate the models and clients for you.
npx @hey-api/openapi-ts \
-i https://get.heyapi.dev/hey-api/backend \
-o src/client \
-c @hey-api/client-fetch
Example model
export type Mandant = {
id?: number;
name: string;
};
Example client
The following example uses axios as a http-client.
export const getMandantById = <ThrowOnError extends boolean = false>(
options: Options<GetMandantByIdData, ThrowOnError>
) => {
return (options.client ?? _heyApiClient)
.get<GetMandantByIdResponse, unknown, ThrowOnError>(
{
url: '/mandant/{id}',
...options
}
);
};
The next step is to call these methods inside your application logic. This is a good approach to creating consistent models and saving writing work. If some DTO is still missing, you can simply enhance the service yourself 👍.
Disclaimer
Photo/Video from DALL - E on https://openai.com/dall-e-3
Keep in mind: Some trademarks mentioned are under copyright.