HomeRessources, Guides & Actualités – Actualités de l’intelligence artificielleMemoOpenAPI Generator : De la Spécification OpenAPI au Code de Production

OpenAPI Generator : De la Spécification OpenAPI au Code de Production

Je transforme des contrats d’interface en code exécutable depuis des années. L’outillage autour de la spécification OpenAPI constitue le pivot de cette démarche. OpenAPI Generator automatise la production de bibliothèques clientes (SDK), de squelettes de serveurs, de documentations interactives et de fichiers de configuration à partir de schémas OpenAPI (versions 2.0 et 3.0).

Une mise au point s’impose. Ni l’organisation parente OpenAPI Tools ni le projet OpenAPI Generator ne possèdent d’affiliation avec l’OpenAPI Initiative (OAI).

Ce projet vit grâce à sa communauté open source.

Attention aux failles de sécurité. Si vous chargez une spécification OpenAPI, des templates ou des variables d’environnement issus d’une source non vérifiée, inspectez chaque élément avant génération. Vous éviterez des injections de code directes. Signalez toute vulnérabilité découverte à l’adresse : team@openapitools.org.

Écosystème des langages et frameworks supportés

Le moteur produit du code pour des dizaines de cibles technologiques.

CatégorieLangages et environnements cibles
Clients d’APIActionScript, Ada, Apex, Bash, C, C# (.NET 2.0, 3.5+, .NET Standard 1.3 – 2.1, .NET Core 3.1, .NET 5.0 avec RestSharp, GenericHost, HttpClient), C++ (Arduino, cpp-restsdk, Qt5, Tizen, Unreal Engine 4), Clojure, Crystal, Dart, Elixir, Elm, Eiffel, Erlang, Go, Groovy, Haskell (http-client, Servant), Java (Apache HttpClient 4.x/5.x, Jersey 2.x, OkHttp, Retrofit 1.x/2.x, Feign, RestTemplate, RESTEasy, Vert.x, Google API Client Library, Rest-assured, Spring 5 Web Client, Spring 6 RestClient, MicroProfile Rest Client, Helidon), Jetbrains HTTP Client, Julia, k6, Kotlin, Lua, N4JS, Nim, Node.js/JavaScript (ES5, ES6, AngularJS avec annotations Google Closure Compiler, Flow types, Apollo GraphQL DataStore), Objective-C, OCaml, Perl, PHP, PowerShell, Python, R, Ruby, Rust (hyper, reqwest, rust-server), Scala (akka, http4s, scalaz, sttp, swagger-async-httpclient, pekko), Swift (2.x à 6.x), TypeScript (AngularJS, Angular 9.x à 19.x, Aurelia, Axios, Fetch, Inversify, jQuery, NestJS, Node, redux-query, RxJS), XoJo, Zapier.
Squelettes Serveurs (Stubs)Ada, C# (ASP.NET Core, Azure Functions), C++ (Httplib, Oat++, Pistache, Restbed, Qt5 QHTTPEngine), Erlang, F# (Giraffe), Go (net/http, Gin, Echo), Haskell (Servant, Yesod), Java (MSF4J, Spring, Undertow, JAX-RS avec CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, PKMST, Vert.x, Apache Camel, Helidon), Julia, Kotlin (Spring Boot, Ktor, Vert.x), PHP (Flight, Laravel, Lumen, Mezzio fka Zend Expressive, Slim, Silex, Symfony), Python (FastAPI, Flask), NodeJS, Ruby (Sinatra, Rails5), Rust (rust-server), Scala (Akka, Finch, Lagom, Play, Cask, Scalatra).
Générateurs de documentationHTML, Confluence Wiki, Asciidoc, Markdown, PlantUML.
Fichiers de configurationApache2.
Autres formatsGraphQL, JMeter, Ktorm, Schéma MySQL, Postman Collection, Protocol Buffer, WSDL.

Matrice de compatibilité

Le projet maintient une compatibilité stricte avec les différentes déclinaisons de la spécification OpenAPI (1.0, 1.1, 1.2, 2.0, 3.0 et support bêta pour 3.1). Aucun build quotidien ou nocturne n’est publié sur les registres officiels.

Utilisez les versions SNAPSHOT pour tester les fonctionnalités en amont.

Version OpenAPI GeneratorDate de sortieRemarques
7.25.0 SNAPSHOT20.08.2026Version mineure avec ruptures de compatibilité (avec mécanisme de repli).
7.24.0 (Stable)20.07.2026Version mineure avec ruptures de compatibilité (avec mécanisme de repli).
6.6.011.05.2023Version mineure avec ruptures de compatibilité (avec mécanisme de repli).
5.4.031.01.2022Version mineure avec ruptures de compatibilité (avec mécanisme de repli).
4.3.106.05.2020Version corrective (correctifs et améliorations).

Consultez la section des pull requests affublées du label Decommission pour identifier les générateurs ou bibliothèques retirés du projet.

Installation et modes de déploiement

Choisissez le mode d’installation adapté à votre infrastructure.

Artefacts Maven Central

Pour intégrer le générateur dans vos chaînes de compilation Java ou Kotlin, déclarez les dépendances appropriées :

Module Core :

<dependency>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator</artifactId>
    <version>7.24.0</version>
</dependency>

Interface en ligne de commande (CLI) :

<dependency>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-cli</artifactId>
    <version>7.24.0</version>
</dependency>

Plugin Maven :

<dependency>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>7.24.0</version>
</dependency>

Plugin Gradle :

<dependency>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-gradle-plugin</artifactId>
    <version>7.24.0</version>
</dependency>

Exécutable binaire JAR

L’exécutable autonome requiert au minimum un environnement Java 11.

Sous Linux et macOS :

wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.24.0/openapi-generator-cli-7.24.0.jar -O openapi-generator-cli.jar
java -jar openapi-generator-cli.jar help

Sous macOS, configurez explicitement votre variable d’environnement Java :

export JAVA_HOME=`/usr/libexec/java_home -v 1.11`
export PATH=${JAVA_HOME}/bin:$PATH

Sous Windows avec PowerShell (version 3.0 ou supérieure) :

Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.24.0/openapi-generator-cli-7.24.0.jar
java -jar openapi-generator-cli.jar help

Script de lancement Bash

Le script utilitaire évite la gestion manuelle des versions. Il interroge l’API GitHub, compare les empreintes des versions et télécharge l’archive binaire manquante.

mkdir -p ~/bin/openapitools
curl https://raw.githubusercontent.com/OpenAPITools/openapi-generator/master/bin/utils/openapi-generator-cli.sh > ~/bin/openapitools/openapi-generator-cli
chmod u+x ~/bin/openapitools/openapi-generator-cli
export PATH=$PATH:~/bin/openapitools/

Pour forcer une version spécifique lors d’une session ou d’une exécution ponctuelle :

# Exécution avec la version courante du dépôt
openapi-generator-cli version

# Exécution isolée en version 4.1.0
OPENAPI_GENERATOR_VERSION=4.1.0 openapi-generator-cli version

# Exécution ciblée sur un build snapshot
OPENAPI_GENERATOR_VERSION=4.1.0-SNAPSHOT openapi-generator-cli version

# Verrouillage pour la session de terminal
export OPENAPI_GENERATOR_VERSION=4.0.2
openapi-generator-cli version

# Verrouillage persistant dans votre profil shell
echo "export OPENAPI_GENERATOR_VERSION=4.0.2" >> ~/.bashrc
source ~/.bashrc

Compilation depuis les sources

Prérequis : Java 11 et Apache Maven 3.8.8 minimum.

Clonez puis compilez avec le wrapper Maven :

# Linux / macOS
./mvnw clean install

# Windows
mvnw.cmd clean install

# Analyse statique enrichie (PMD, CheckStyle, Spotbugs)
./mvnw -Pstatic-analysis clean install

Pour les utilisateurs de Nix et Direnv :

# Entrer dans le shell de développement préconfiguré
nix develop

# Chargement sans action manuelle via direnv
direnv allow

Gestionnaires de paquets (Homebrew, NPM, Pip)

Installation avec Homebrew sur macOS :

brew install openapi-generator

# Installer la branche master active
brew uninstall openapi-generator && brew install --HEAD openapi-generator

# Installation du SDK Java si nécessaire
brew tap AdoptOpenJDK/openjdk
brew install --cask adoptopenjdk11
export JAVA_HOME=`/usr/libexec/java_home -v 1.11`
brew install maven

Installation avec NPM (nécessite une JVM locale) :

# Installation globale
npm install @openapitools/openapi-generator-cli -g
openapi-generator-cli version

# Définir une version précise du moteur
openapi-generator-cli version-manager set 7.24.0

# Installation locale dans un projet Node
npm install @openapitools/openapi-generator-cli -D

Installation avec Python Pip :

pip install openapi-generator-cli
pip install openapi-generator-cli==7.24.0

# Version autonome embarquant une JVM (Python 3.10+ requis)
pip install openapi-generator-cli[jdk4py]

Conteneurs Docker

Deux images officielles existent sur le registre public :

Génération de code Go avec l’image CLI isolée :

docker run --rm -v "${PWD}:/local" openapitools/openapi-generator-cli generate \
    -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml \
    -g go \
    -o /local/out/go

Exploitation du serveur Web conteneurisé :

# Démarrage du conteneur en arrière-plan
CID=$(docker run -d -p 8888:8080 openapitools/openapi-generator-online)
sleep 10

# Requête de génération pour un client Ruby
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' \
-d '{"openAPIUrl": "https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml"}' \
'http://localhost:8888/api/gen/clients/ruby'

# Réponse reçue : {"code":"c2d483.3.4672-40e9-91df-b9ffd18d22b8","link":"http://localhost:8888/api/gen/download/c2d483.3.4672-40e9-91df-b9ffd18d22b8"}

# Téléchargement de l'archive ZIP générée
wget http://localhost:8888/api/gen/download/c2d483.3.4672-40e9-91df-b9ffd18d22b8
unzip c2d483.3.4672-40e9-91df-b9ffd18d22b8

# Arrêt du conteneur
docker stop $CID && docker rm $CID

Développement interne avec run-in-docker.sh :

git clone https://github.com/openapitools/openapi-generator
cd openapi-generator
./run-in-docker.sh mvn package
./run-in-docker.sh help
./run-in-docker.sh list
./run-in-docker.sh generate -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml \
    -g go -o /gen/out/go-petstore -p packageName=petstore

Résolution des pannes de build dans Docker :

# En cas d'erreur Surefire / ExceptionInInitializerError :
./run-in-docker.sh mvn clean install -U

Note sur l’échec org.gradle.tooling.BuildException via gradle-maven-plugin : aucune solution n’est disponible actuellement.

Exécution via Vagrant :

git clone https://github.com/openapitools/openapi-generator.git
cd openapi-generator
vagrant up
vagrant ssh
cd /vagrant
./run-in-docker.sh mvn package

Guide d’utilisation et commandes CLI

La commande principale generate transforme votre schéma source. Voici la syntaxe d’inspection et de création :

# Lister les options globales de génération
java -jar openapi-generator-cli.jar help generate

# Obtenir les réglages spécifiques d'un langage (ex: PHP)
java -jar openapi-generator-cli.jar config-help -g php

# Générer un client PHP complet
java -jar openapi-generator-cli.jar generate \
   -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml \
   -g php \
   -o /var/tmp/php_api_client

Pour un poste Windows, ajustez le chemin de destination : -o c:\temp\php_api_client.

Options détaillées du moteur CLI

openapi-generator-cli generate
        [(-a <authorization> | --auth <authorization>)]
        [--api-name-suffix <api name suffix>] [--api-package <api package>]
        [--artifact-id <artifact id>] [--artifact-version <artifact version>]
        [(-c <configuration file> | --config <configuration file>)] [--dry-run]
        [(-e <templating engine> | --engine <templating engine>)]
        [--enable-post-process-file]
        [(-g <generator name> | --generator-name <generator name>)]
        [--generate-alias-as-model] [--git-host <git host>]
        [--git-repo-id <git repo id>] [--git-user-id <git user id>]
        [--global-property <global properties>...] [--group-id <group id>]
        [--http-user-agent <http user agent>]
        [(-i <spec file> | --input-spec <spec file>)]
        [--ignore-file-override <ignore file override location>]
        [--import-mappings <import mappings>...]
        [--instantiation-types <instantiation types>...]
        [--invoker-package <invoker package>]
        [--language-specific-primitives <language specific primitives>...]
        [--legacy-discriminator-behavior] [--library <library>]
        [--log-to-stderr] [--minimal-update]
        [--model-name-prefix <model name prefix>]
        [--model-name-suffix <model name suffix>]
        [--model-package <model package>]
        [(-o <output directory> | --output <output directory>)]
        [(-p <additional properties> | --additional-properties <additional properties>)...]
        [--package-name <package name>] [--release-note <release note>]
        [--remove-operation-id-prefix]
        [--reserved-words-mappings <reserved word mappings>...]
        [(-s | --skip-overwrite)] [--server-variables <server variables>...]
        [--skip-validate-spec] [--strict-spec <true/false strict behavior>]
        [(-t <template directory> | --template-dir <template directory>)]
        [--type-mappings <type mappings>...] [(-v | --verbose)]

Cas pratique : Génération d’un client Java OkHttp-Gson

Le dépôt contient des configurations d’exemples prêtes à l’emploi. Lancez le script de démonstration :

./bin/generate-samples.sh ./bin/configs/java-okhttp-gson.yaml

Cette commande exécute sous le capot les arguments suivants :

java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate \
  -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml \
  -g java \
  -t modules/openapi-generator/src/main/resources/Java \
  --additional-properties artifactId=petstore-okhttp-gson,hideGenerationTimestamp=true \
  -o samples/client/petstore/java/okhttp-gson

Rendez-vous dans le répertoire de sortie pour compiler et exécuter la suite de tests :

cd samples/client/petstore/java/okhttp-gson
mvn package

Personnalisation et intégrations CI/CD

Le comportement du générateur se configure via des fichiers YAML ou JSON passés avec l’option -c. Vous pouvez modifier le nom du package, injecter des types personnalisés avec --type-mappings ou surcharger les gabarits Mustache grâce au flag -t.

Pour vos pipelines automatisés, le générateur s’intègre avec Maven, Gradle, SBT, Bazel, GitHub Actions et l’ensemble des plateformes CI/CD.

Deux instances d’évaluation en ligne hébergées par Linode restent accessibles sans garantie de service :

Intégrations IDE communautaires

  • Eclipse : Codewind OpenAPI Tools for Eclipse (par IBM).
  • IntelliJ IDEA : OpenAPI Generator (par Jim Schubert).
  • IntelliJ IDEA : Senya Editor (par senya.io).
  • RepreZen API Studio.
  • Visual Studio : REST API Client Code Generator (par Christian Resma Helle).
  • Visual Studio Code : Codewind OpenAPI Tools (par IBM).

Propriété intellectuelle et licence du code généré

Les gabarits fournis dans le projet respectent la licence logicielle du dépôt parent. En revanche, le code source issu de la génération appartient intégralement à l’utilisateur du logiciel. Ce code est fourni tel quel, sans garantie explicite ou implicite. Vous appliquez les termes de licence de votre choix sur les bibliothèques produites.

Leave a Reply

Your email address will not be published. Required fields are marked *