# OpenAPI Generator OpenAPI Generator is a powerful code generation tool that automatically creates API client libraries, server stubs, API documentation, and configuration files from OpenAPI Specification (formerly Swagger) documents. Supporting both OpenAPI 2.0 and 3.x specifications, it generates production-ready code for over 50 programming languages and frameworks including Java, Python, TypeScript, Go, Ruby, PHP, C#, Kotlin, Swift, and many more. The tool provides multiple integration options: a standalone CLI for direct usage, Maven and Gradle plugins for Java build systems, an NPM wrapper for Node.js environments, Docker images for containerized workflows, and an online REST API for web-based generation. This flexibility allows teams to integrate API code generation into any development workflow, from local development to CI/CD pipelines, ensuring type-safe API consumption and reducing manual coding effort when working with REST APIs. ## CLI Commands ### Generate Code The primary command for generating API clients, server stubs, or documentation from an OpenAPI specification. ```bash # Generate a Java client from a remote OpenAPI spec openapi-generator-cli generate \ -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml \ -g java \ -o ./generated/java-client \ --additional-properties=artifactId=petstore-client,groupId=com.example # Generate a TypeScript-Axios client with custom options openapi-generator-cli generate \ -i ./api-spec.yaml \ -g typescript-axios \ -o ./src/api \ --additional-properties=npmName=@myorg/api-client,npmVersion=1.0.0,supportsES6=true # Generate a Spring Boot server stub openapi-generator-cli generate \ -i petstore.yaml \ -g spring \ -o ./server \ --additional-properties=library=spring-boot,delegatePattern=true,useTags=true # Generate with custom type mappings (e.g., DateTime to LocalDateTime) openapi-generator-cli generate \ -i petstore.yaml \ -g kotlin-spring \ -o ./out \ --type-mappings=DateTime=java.time.LocalDateTime \ --import-mappings=DateTime=java.time.LocalDateTime # Generate only models (selective generation) openapi-generator-cli generate \ -i petstore.yaml \ -g java \ -o ./models \ --global-property models="User:Pet" # Dry run to preview what would be generated openapi-generator-cli generate -i petstore.yaml -g python -o ./out --dry-run ``` ### List Available Generators Display all available code generators for clients, servers, documentation, schemas, and configuration. ```bash # List all generators in formatted output openapi-generator-cli list # List generators in CSV format for scripting openapi-generator-cli list -s # Sample output: # CLIENT generators: ada, android, apex, bash, c, clojure, cpp-qt, csharp, dart, # elixir, go, groovy, haskell-http-client, java, javascript, # kotlin, perl, php, python, ruby, rust, scala-akka, swift5, # swift6, typescript-angular, typescript-axios, typescript-fetch... # SERVER generators: aspnetcore, go-server, java-spring, kotlin-spring, nodejs-express, # php-laravel, python-fastapi, python-flask, rust-axum, spring... ``` ### Get Generator Configuration Options Display available configuration options for a specific generator. ```bash # Get config options for the Java generator openapi-generator-cli config-help -g java # Sample output: # CONFIG OPTIONS # artifactId: artifactId in generated pom.xml (Default: openapi-java-client) # library: library template (sub-template) to use: # - apache-httpclient (default) # - feign # - jersey2 # - native (Java 11 native HTTP client) # - okhttp-gson # - restclient # - resttemplate # - retrofit2 # - webclient # dateLibrary: date library to use: # - java8 (default) # - java8-localdatetime # - legacy # Get config options for Python generator openapi-generator-cli config-help -g python # Get full details including import mappings and reserved words openapi-generator-cli config-help -g typescript-axios --full-details # Output to markdown format (useful for documentation) openapi-generator-cli config-help -g go -f markdown -o ./docs/go-options.md ``` ### Validate OpenAPI Specification Validate an OpenAPI specification file for errors and get recommendations. ```bash # Validate a local spec file openapi-generator-cli validate -i ./api-spec.yaml # Output: Validating spec (./api-spec.yaml) # No validation issues detected. # Validate a remote spec openapi-generator-cli validate -i https://api.example.com/openapi.json # Validate with recommendations openapi-generator-cli validate -i ./api-spec.yaml --recommend # Output: Validating spec (./api-spec.yaml) # Errors: # - attribute info is missing # [error] Spec has 1 errors. ``` ### Extract Templates for Customization Extract built-in templates to customize code generation output. ```bash # Extract all Java templates openapi-generator-cli author template -g java -o ./my-templates # Extract templates for a specific library openapi-generator-cli author template -g java --library webclient -o ./webclient-templates # Extract TypeScript templates openapi-generator-cli author template -g typescript-fetch -o ./ts-templates # Then use custom templates when generating: openapi-generator-cli generate \ -i petstore.yaml \ -g java \ -o ./out \ -t ./my-templates ``` ### Create Custom Generator Create a new custom generator project scaffold using the meta command. ```bash # Create a new generator called "my-codegen" java -jar openapi-generator-cli.jar meta \ -o ./generators/my-codegen \ -n my-codegen \ -p com.mycompany.codegen # This creates: # ./generators/my-codegen/ # ├── pom.xml # ├── src/main/java/com/mycompany/codegen/MyCodegenGenerator.java # ├── src/main/resources/my-codegen/api.mustache # └── README.md # Build and use your custom generator cd ./generators/my-codegen && mvn package java -cp target/my-codegen-1.0.0.jar:openapi-generator-cli.jar \ org.openapitools.codegen.OpenAPIGenerator generate \ -g my-codegen -i petstore.yaml -o ./out ``` ## Maven Plugin ### Basic Maven Integration Add the OpenAPI Generator Maven plugin to generate code during the build process. ```xml org.openapitools openapi-generator-maven-plugin 7.21.0 generate ${project.basedir}/src/main/resources/api.yaml java ${project.build.directory}/generated-sources/openapi com.example.api com.example.model com.example.invoker src/gen/java/main native java8 true serializableModel=true ``` ### Advanced Maven Configuration with Type Mappings Configure type mappings and import mappings for customized code generation. ```xml org.openapitools openapi-generator-maven-plugin 7.21.0 generate ${project.basedir}/src/main/resources/openapi.yaml spring ${project.build.directory}/generated-sources Double=java.math.BigDecimal binary=StreamingOutput DateTime=java.time.LocalDateTime StreamingOutput=javax.ws.rs.core.StreamingOutput LocalDateTime=java.time.LocalDateTime true true false false Pet:User:Order spring-boot true true true ``` ### Maven Plugin with Custom Generator Use a custom generator by adding it as a plugin dependency. ```xml org.openapitools openapi-generator-maven-plugin 7.21.0 generate ${project.basedir}/src/main/resources/api.yaml com.mycompany.codegen.MyCodegenGenerator myTemplateDir ${project.build.directory}/generated-sources com.example.api com.example.model com.mycompany my-codegen-openapi-generator 1.0.0 ``` ## Gradle Plugin ### Basic Gradle Integration Configure the OpenAPI Generator Gradle plugin for code generation. ```groovy // build.gradle plugins { id "org.openapi.generator" version "7.21.0" } openApiGenerate { // Input specification inputSpec = "$rootDir/src/main/resources/api.yaml" // Generator to use generatorName = "kotlin" // Output directory outputDir = "$buildDir/generated" // Package configuration apiPackage = "com.example.api" modelPackage = "com.example.model" invokerPackage = "com.example.invoker" // Generator-specific configuration configOptions = [ dateLibrary: "java8", serializableModel: "true", library: "jvm-okhttp4" ] // Type mappings typeMappings = [ "DateTime": "java.time.LocalDateTime" ] // Additional properties additionalProperties = [ "removeEnumValuePrefix": "false" ] } // Add generated sources to compilation sourceSets { main { java { srcDir "$buildDir/generated/src/main/kotlin" } } } compileKotlin.dependsOn tasks.openApiGenerate ``` ### Gradle Kotlin DSL Configuration Configure the plugin using Kotlin DSL syntax. ```kotlin // build.gradle.kts plugins { id("org.openapi.generator") version "7.21.0" } openApiGenerate { inputSpec.set("$rootDir/src/main/resources/openapi.yaml") generatorName.set("typescript-axios") outputDir.set("$buildDir/generated-ts") configOptions.set(mapOf( "npmName" to "@myorg/api-client", "npmVersion" to "1.0.0", "supportsES6" to "true", "withSeparateModelsAndApi" to "true" )) additionalProperties.set(mapOf( "useSingleRequestParameter" to "true" )) } openApiValidate { inputSpec.set("$rootDir/src/main/resources/openapi.yaml") } // Custom validation task tasks.register("validateProdSpec") { inputSpec.set("$rootDir/specs/production-api.yaml") } ``` ### Multiple Generator Tasks in Gradle Define multiple generation tasks for different targets. ```groovy // build.gradle plugins { id "org.openapi.generator" version "7.21.0" } // Generate Java client task generateJavaClient(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask) { inputSpec = "$rootDir/api.yaml" generatorName = "java" outputDir = "$buildDir/generated/java-client" apiPackage = "com.example.client.api" modelPackage = "com.example.client.model" configOptions = [ library: "native", dateLibrary: "java8" ] } // Generate TypeScript client task generateTypescriptClient(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask) { inputSpec = "$rootDir/api.yaml" generatorName = "typescript-fetch" outputDir = "$buildDir/generated/ts-client" configOptions = [ supportsES6: "true", typescriptThreePlus: "true" ] } // Generate Spring server task generateSpringServer(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask) { inputSpec = "$rootDir/api.yaml" generatorName = "spring" outputDir = "$buildDir/generated/spring-server" configOptions = [ library: "spring-boot", delegatePattern: "true", interfaceOnly: "true" ] } // Run all generators task generateAll(dependsOn: ['generateJavaClient', 'generateTypescriptClient', 'generateSpringServer']) ``` ## Configuration File ### YAML Configuration Create a configuration file for complex generator settings. ```yaml # config.yaml generatorName: java inputSpec: https://petstore.swagger.io/v2/swagger.json outputDir: ./generated # Package configuration apiPackage: com.example.petstore.api modelPackage: com.example.petstore.model invokerPackage: com.example.petstore.invoker # Generator-specific options additionalProperties: artifactId: petstore-client groupId: com.example library: native dateLibrary: java8 serializableModel: "true" hideGenerationTimestamp: "true" useJakartaEe: "true" # Type mappings typeMappings: DateTime: java.time.OffsetDateTime # Import mappings importMappings: OffsetDateTime: java.time.OffsetDateTime # Generation control generateApiTests: false generateModelTests: false generateApiDocumentation: true generateModelDocumentation: true # Use with: openapi-generator-cli generate -c config.yaml ``` ### JSON Configuration Alternative JSON format for configuration. ```json { "generatorName": "typescript-axios", "inputSpec": "./api-spec.yaml", "outputDir": "./src/generated", "additionalProperties": { "npmName": "@myorg/petstore-api", "npmVersion": "1.0.0", "supportsES6": true, "withSeparateModelsAndApi": true, "apiPackage": "api", "modelPackage": "models" }, "typeMappings": { "DateTime": "Date" }, "globalProperties": { "apiDocs": false, "modelDocs": false } } ``` ## Online API / Docker ### REST API for Code Generation Use the hosted online service or self-hosted Docker instance for code generation. ```bash # Generate Ruby client using hosted API curl -X POST --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ -d '{"openAPIUrl": "https://petstore.swagger.io/v2/swagger.json"}' \ 'https://api.openapi-generator.tech/api/gen/clients/ruby' # Response: # { # "code": "c2d483-40e9-91df-b9ffd18d22b8", # "link": "https://api.openapi-generator.tech/api/gen/download/c2d483-40e9-91df-b9ffd18d22b8" # } # Download generated code wget https://api.openapi-generator.tech/api/gen/download/c2d483-40e9-91df-b9ffd18d22b8 -O ruby-client.zip # Generate with custom options curl -X POST -H "Content-type: application/json" \ -d '{ "openAPIUrl": "https://petstore.swagger.io/v2/swagger.json", "options": { "packageName": "petstore_client", "gemName": "petstore_api" } }' \ https://api.openapi-generator.tech/api/gen/clients/ruby # Get available options for a generator curl https://api.openapi-generator.tech/api/gen/clients/python # Generate with inline spec (no URL) curl -X POST -H "Content-type: application/json" \ -d '{ "spec": { "openapi": "3.0.0", "info": {"title": "My API", "version": "1.0.0"}, "paths": { "/users": { "get": { "operationId": "getUsers", "responses": {"200": {"description": "Success"}} } } } }, "options": {"packageName": "my_api_client"} }' \ https://api.openapi-generator.tech/api/gen/clients/python ``` ### Docker Usage Run OpenAPI Generator using the official Docker image. ```bash # Generate Go client using Docker docker run --rm \ -v "${PWD}:/local" \ openapitools/openapi-generator-cli generate \ -i https://petstore.swagger.io/v2/swagger.json \ -g go \ -o /local/out/go-client # Generate from local spec file docker run --rm \ -v "${PWD}:/local" \ openapitools/openapi-generator-cli generate \ -i /local/api-spec.yaml \ -g typescript-fetch \ -o /local/generated/ts-client # List available generators docker run --rm openapitools/openapi-generator-cli list # Validate specification docker run --rm \ -v "${PWD}:/local" \ openapitools/openapi-generator-cli validate \ -i /local/api-spec.yaml # Run self-hosted online generator docker run -d -p 8080:8080 openapitools/openapi-generator-online # Then use local API: curl -X POST -H "Content-type: application/json" \ -d '{"openAPIUrl": "https://petstore.swagger.io/v2/swagger.json"}' \ http://localhost:8080/api/gen/clients/java ``` ## NPM Wrapper ### NPM CLI Installation and Usage Use the NPM wrapper for Node.js environments. ```bash # Install globally npm install @openapitools/openapi-generator-cli -g # Set specific version openapi-generator-cli version-manager set 7.21.0 # Generate TypeScript client openapi-generator-cli generate \ -i https://petstore.swagger.io/v2/swagger.json \ -g typescript-axios \ -o ./src/api # Install as dev dependency npm install @openapitools/openapi-generator-cli -D # Add to package.json scripts # { # "scripts": { # "generate:api": "openapi-generator-cli generate -c openapi-config.yaml", # "validate:api": "openapi-generator-cli validate -i ./api-spec.yaml" # } # } # Run via npx npx @openapitools/openapi-generator-cli generate \ -i api.yaml \ -g javascript \ -o ./generated # Configuration file for npm wrapper (openapitools.json) # { # "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json", # "spaces": 2, # "generator-cli": { # "version": "7.21.0", # "generators": { # "v1": { # "generatorName": "typescript-axios", # "output": "./src/api/v1", # "inputSpec": "./specs/api-v1.yaml" # } # } # } # } ``` ## Batch Generation ### Batch Configuration Generate multiple clients/servers in a single command using batch mode. ```yaml # shared/common.yaml inputSpec: https://petstore.swagger.io/v2/swagger.json additionalProperties: hideGenerationTimestamp: "true" --- # java-client.yaml '!include': 'shared/common.yaml' outputDir: out/java-client generatorName: java artifactId: petstore-java-client additionalProperties: library: native dateLibrary: java8 --- # python-client.yaml '!include': 'shared/common.yaml' outputDir: out/python-client generatorName: python additionalProperties: packageName: petstore_client projectName: petstore-python-client --- # typescript-client.yaml '!include': 'shared/common.yaml' outputDir: out/ts-client generatorName: typescript-axios additionalProperties: npmName: "@myorg/petstore-client" supportsES6: "true" ``` ```bash # Generate all clients in batch openapi-generator-cli batch java-client.yaml python-client.yaml typescript-client.yaml # Run in parallel with 4 threads openapi-generator-cli batch --threads 4 *.yaml # With shared includes directory openapi-generator-cli batch --includes-base-dir ./shared *.yaml # Fail fast on first error openapi-generator-cli batch --fail-fast *.yaml ``` OpenAPI Generator serves as an essential tool in API-first development workflows, enabling teams to maintain consistency between API specifications and implementation code. Common use cases include generating type-safe API clients for frontend applications (React, Angular, Vue with TypeScript), creating server stubs for rapid backend prototyping (Spring Boot, FastAPI, Express), producing SDK libraries for API distribution, and generating documentation from OpenAPI specs. The tool integrates seamlessly into CI/CD pipelines to ensure generated code stays synchronized with API changes. The generator supports extensive customization through template overrides, custom generators, and configuration options, allowing teams to tailor generated code to match existing coding standards and architectural patterns. For microservices architectures, batch generation enables simultaneous creation of clients for multiple services, while schema generators can produce database schemas, GraphQL types, or Protocol Buffers from OpenAPI definitions. Whether used for internal API development or public API SDK distribution, OpenAPI Generator significantly reduces boilerplate code and ensures type safety across the entire API integration surface.