OpenAPI from Code
When your API is written in code first, the framework can describe it as an OpenAPI document. This page shows how a Spring Boot, NestJS or FastAPI build writes that document to a file. routebase spec push then writes the file into the draft of your spec in Routebase.
Pushing requires an API key with specs:write and specs:delete plus access to the project. A dry run requires specs:read.
The push reads the file in JSON or YAML, and it accepts OpenAPI 3.0 and 3.1. Each recipe below produces one of the two versions without extra settings.
Spring Boot
springdoc-openapi serves the document of a running Spring Boot app at /v3/api-docs, and as YAML at /v3/api-docs.yaml. Its Maven and Gradle plugins start the app during the build, download that document and write it to a file. The app therefore needs the springdoc-openapi dependency, and it must be able to start in your CI job.
springdoc-openapi writes OpenAPI 3.1 by default. The property springdoc.api-docs.version switches it to 3.0.
With Maven
Add both plugins to the <build><plugins> section of your pom.xml. The Spring Boot plugin starts the app before the integration tests and stops it afterwards, and the springdoc plugin downloads the document in between.
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<jvmArguments>-Dspring.application.admin.enabled=true</jvmArguments>
</configuration>
<executions>
<execution>
<id>pre-integration-test</id>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>post-integration-test</id>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-maven-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<failOnError>true</failOnError>
</configuration>
</plugin>
Then run the build:
mvn verify
The document is written to target/openapi.json. Without failOnError, the plugin only logs a failed download and the build goes on without the file, so keep the setting on in CI.
With Gradle
Add the plugin next to the Spring Boot plugin that your build already applies:
plugins {
id("org.springdoc.openapi-gradle-plugin") version "2.1.0"
}
Then run the task:
./gradlew generateOpenApiDocs
The task starts the app, writes the document to build/openapi.json and stops the app again. The openApi block changes the defaults, for example outputDir and outputFileName.
Writing YAML instead of JSON
Both plugins take the same two settings. Point apiDocsUrl at http://localhost:8080/v3/api-docs.yaml and set outputFileName to openapi.yaml.
NestJS
@nestjs/swagger builds the document from your controllers with SwaggerModule.createDocument(). The result is a plain object, so a short script can write it to a file without starting the server.
Install the package if your app doesn't use it yet:
npm install --save @nestjs/swaggerAdd a script next to
main.ts, for examplesrc/generate-openapi.ts. It creates the application, builds the document and writes it as JSON, without listening on a port.import { writeFileSync } from 'node:fs'; import { NestFactory } from '@nestjs/core'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; import { AppModule } from './app.module.js'; async function generate() { const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle('Orders API') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, config); writeFileSync('openapi.json', JSON.stringify(document, null, 2)); await app.close(); } await generate();The script uses the ES module form of a new Nest project, so follow the form of your own
main.ts. A project that compiles to CommonJS can't use a top-levelawait. There, write the import the way yourmain.tsdoes, such as./app.modulewithout the.jssuffix, and end the script withgenerate()instead ofawait generate().Build the project and run the compiled script. In a project created with the Nest CLI, the build writes to
dist.npm run build node dist/generate-openapi.js
The file openapi.json appears in the directory you run the command from. If main.ts calls app.enableVersioning(), call it in the script too, before createDocument(). Otherwise the paths in the document are missing the version prefix.
@nestjs/swagger writes OpenAPI 3.0 unless you set another version with setOpenAPIVersion() on the DocumentBuilder.
FastAPI
A FastAPI app returns its OpenAPI document from app.openapi() as a Python dictionary. A script that imports the app can write it to a file without starting a server.
Add a script to your project, for example
export_openapi.py. Replaceapp.mainwith the module that defines yourFastAPIinstance.import json from app.main import app with open("openapi.json", "w") as f: json.dump(app.openapi(), f, indent=2)Run it in the environment where your app's dependencies are installed:
python export_openapi.py
FastAPI writes OpenAPI 3.1 by default.
Pushing the file
Once the build has written the file, push it into the draft of your spec:
routebase spec push orders --file target/openapi.json --project <project-id>
The spec accepts a name or an id. Endpoints are matched by method and path, so the tests, mock rules and monitors linked to them stay linked. When the push goes through, what the file no longer contains is removed from the draft. A removed endpoint is a breaking change, so it needs a decision first.
On a pull request, add --dry-run. It prints what the push would add, change and remove, and it marks breaking changes without writing anything.
routebase spec push orders --file target/openapi.json --project <project-id> --dry-run
CLI in CI/CD covers the other options, the exit codes of the push and a complete pipeline job.
Limits
The generated document is only as exact as the annotations and types in your code. When an endpoint declares no response type or no description, the document has none either, and so does the spec after the push.
Troubleshooting
The push exits with code 2. The file is not valid OpenAPI, or the build did not write it. The output names the problems, so fix them in the code that produces the document.
The Maven build passes, but target/openapi.json is missing. The plugin could not download the document and only logged it. Set failOnError to true so the build fails with the reason.
The Gradle task fails with The application exited with code …. The app could not start during the build. Its output above the error names the reason, such as a missing database or setting in the CI job.
Related
- CLI in CI/CD — exit codes, dry runs and a complete pipeline job
- CLI Overview — installing and configuring the CLI
- Import & Export — what the file owns and what Routebase keeps
- API Keys — creating a key with the permissions the push needs