Getting Started with Serverpod Swagger
Serverpod Swagger generates OpenAPI 3.0 specifications from your Serverpod endpoint classes and model definitions, and serves a Swagger UI interface directly from your server.
Prerequisites
- Dart SDK >= 3.5.0
- Serverpod >= 3.4.2
- A working Serverpod project
Installation
Add the package to your server project's pubspec.yaml:
pubspec.yaml
1dependencies:
2 serverpod: ">=3.4.2 <4.0.0"
3 serverpod_swagger: ^1.0.0Then run:
dart pub getSetup
1. Import the package
server.dart
1import 'dart:io';
2import 'package:serverpod/serverpod.dart';
3import 'package:serverpod_swagger/serverpod_swagger.dart';2. Register the Swagger UI route
Add two route registrations: one with the wildcard pattern for sub-paths, and one for the base path to handle the redirect from /swagger to /swagger/.
server.dart
1void run(List<String> args) async {
2 final pod = Serverpod(
3 args,
4 Protocol(),
5 Endpoints(),
6 );
7
8 // Add the Swagger UI route
9 final swaggerRoute = SwaggerUIRoute(Directory.current);
10 pod.webServer.addRoute(swaggerRoute, '/swagger/**');
11 pod.webServer.addRoute(swaggerRoute, '/swagger');
12
13 await pod.start();
14}3. Generate the OpenAPI specification
Run the generator from your project root. It analyzes your endpoint classes and model files to produce apispec.json.
dart run serverpod_swagger:generate4. Start your server and open Swagger UI
Start your Serverpod server and navigate to http://localhost:8082/swagger/ in your browser.
Tip: Navigating to /swagger (without trailing slash) will automatically redirect to /swagger/.
How It Works
- The CLI generator uses the Dart analyzer to parse your endpoint classes under
lib/src/generated/endpoints/and your model YAML files underlib/src/models/. - HTTP methods are automatically inferred from method names (e.g.,
getUserbecomes GET,createUserbecomes POST,updateUserbecomes PATCH,deleteUserbecomes DELETE). - The Swagger UI route reads
apispec.jsonfrom disk on every request, so changes appear immediately after regenerating. - Swagger UI is loaded from the unpkg CDN (v5.18.2) -- nothing is bundled in the package.