Introduction
OpenAPI 3.1 represents a major evolution for API documentation. This version fully integrates JSON Schema 2020-12, supports native webhooks, and improves schema validation. In a professional context, mastering OpenAPI 3.1 allows generating reliable client/server code, reducing contract errors, and automating tests. This tutorial guides you step by step towards an expert and production-ready implementation.
Prerequisites
- Node.js 20+ and TypeScript 5.4+
- Advanced knowledge of JSON Schema and REST
- Tools: openapi-generator-cli, @apidevtools/swagger-parser
- YAML and webhook concepts
Initialize the OpenAPI Project
mkdir openapi-3.1-project && cd openapi-3.1-project
npm init -y
npm install -D @apidevtools/swagger-parser openapi-generator-cli typescript
npx openapi-generator-cli versionThis command initializes a TypeScript project and installs validation and code generation tools for OpenAPI 3.1. Swagger Parser ensures strict compliance with the 3.1 specification.
Create the Base OpenAPI 3.1 Specification
openapi: 3.1.0
info:
title: User Management API
version: 2.0.0
description: API experte avec JSON Schema 2020-12
servers:
- url: https://api.example.com/v2
paths:
/users/{id}:
get:
operationId: getUserById
parameters:
- name: id
in: path
required: true
schema:
type: string
format: uuid
responses:
'200':
description: Utilisateur récupéré
content:
application/json:
schema:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: string
format: uuid
email:
type: string
format: email
required: [id, email]This file defines a valid OpenAPI 3.1 specification. Version 3.1.0 enables advanced JSON Schema features. Each field is strictly typed to guarantee precise code generation.
Implement Native Webhooks
webhooks:
userCreated:
post:
operationId: userCreatedWebhook
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/User'
responses:
'200':
description: Webhook reçuWebhooks are declared at the root level in 3.1. This allows documenting push events without classic REST endpoints and facilitates client-side listener generation.
Use JSON Schema 2020-12
components:
schemas:
User:
type: object
properties:
id:
type: string
format: uuid
metadata:
type: object
properties:
preferences:
type: array
items:
type: string
minItems: 1
uniqueItems: true
dependentRequired:
email: [verified]
unevaluatedProperties: falseOpenAPI 3.1 supports JSON Schema 2020-12 keywords such as dependentRequired and unevaluatedProperties. These constraints strengthen strict validation and prevent unexpected data in production.
Validate the Specification
import SwaggerParser from '@apidevtools/swagger-parser';
async function validateSpec() {
try {
const api = await SwaggerParser.validate('openapi.yaml');
console.log('Spécification OpenAPI 3.1 valide');
console.log(`Version: ${api.openapi}`);
} catch (err) {
console.error('Erreur de validation:', err);
process.exit(1);
}
}
validateSpec();This TypeScript script validates full compliance with OpenAPI 3.1. It detects schema errors and broken references before any code generation.
Generate the TypeScript Client Code
npx openapi-generator-cli generate \
-i openapi.yaml \
-g typescript-fetch \
-o ./generated-client \
--additional-properties=supportsES6=true,typescriptThreePlus=trueThe generation produces a typed TypeScript client ready for production. The ES6 and TypeScript 3+ options ensure optimal compatibility with modern projects.
Best Practices
- Always use openapi: 3.1.0 and JSON Schema 2020-12 for strict validation
- Centralize reusable schemas in components/schemas
- Systematically document webhooks and securitySchemes
- Automate validation in the CI/CD pipeline
- Version specs with SemVer
Common Errors to Avoid
- Using JSON Schema 2019-09 keywords incompatible with 3.1
- Omitting the webhooks key at the root level
- Ignoring unevaluatedProperties which allows undeclared fields
- Failing to validate the spec before code generation
Going Further
Deepen your skills with our advanced API training.