0
0
Spring Bootframework~5 mins

Generating client code from spec in Spring Boot

Choose your learning style9 modes available
Introduction

Generating client code from a spec helps you quickly create code that talks to an API without writing it all by hand.

You want to call a web service described by an OpenAPI or Swagger file.
You need to avoid manual coding errors when working with APIs.
You want to save time by generating ready-to-use client classes.
You want your client code to stay in sync with API changes automatically.
Syntax
Spring Boot
openapi-generator-cli generate -i <spec-file.yaml> -g java -o <output-folder> --library spring-boot
Replace with your API specification file path.
The -g java option tells the tool to generate Java client code.
Use --library spring-boot to generate Spring Boot specific client code.
Examples
This command generates Spring Boot client code from api-spec.yaml into the ./client folder.
Spring Boot
openapi-generator-cli generate -i api-spec.yaml -g java -o ./client --library spring-boot
Generates client code directly from a remote API spec URL.
Spring Boot
openapi-generator-cli generate -i https://example.com/api.yaml -g java -o ./client --library spring-boot
Generates client code using Spring WebClient instead of RestTemplate.
Spring Boot
openapi-generator-cli generate -i api-spec.yaml -g java -o ./client --library webclient
Sample Program

This example shows how to generate client code from the petstore.yaml spec. Then it uses the generated PetApi class to get a pet by ID and print its name.

Spring Boot
openapi-generator-cli generate -i petstore.yaml -g java -o ./petstore-client --library spring-boot

// After generation, import the generated client in your Spring Boot app

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.petstore.client.api.PetApi;
import com.example.petstore.client.model.Pet;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);

        PetApi petApi = new PetApi();
        Pet pet = petApi.getPetById(1L);
        System.out.println("Pet name: " + pet.getName());
    }
}
OutputSuccess
Important Notes

Make sure you have openapi-generator-cli installed before running commands.

Generated code may need some configuration like base URL or authentication setup.

Keep your spec file updated to regenerate client code when API changes.

Summary

Generating client code saves time and reduces errors when calling APIs.

Use openapi-generator-cli with your API spec and the java generator.

Generated code can be used directly in your Spring Boot projects.