Getting Started with Serverpod Swagger
Serverpod Swagger is a package that automatically generates OpenAPI specifications from your Serverpod protocol definitions and serves a Swagger UI interface directly from your Serverpod server.
Prerequisites
Before you begin, make sure you have:
- Serverpod 2.8.0 or higher
- Dart 3.0.0 or higher
- A working Serverpod project
Installation
Add the package to your pubspec.yaml
file:
1dependencies:
2 serverpod: ^2.8.0
3 serverpod_swagger: ^0.1.5
Then run:
dart pub get
Basic Setup
To add Swagger UI to your Serverpod server, follow these steps:
1. Import the package
1import 'dart:io';
2import 'package:serverpod/serverpod.dart';
3import 'package:serverpod_swagger/serverpod_swagger.dart';
2. Add the Swagger UI route to your server
1// In your server's main.dart file
2
3future<void> main() async {
4 // Create the server
5 final pod = Serverpod(
6 // ... your configuration
7 );
8
9 // Add the Swagger UI route
10 pod.webServer.addRoute(
11 SwaggerUIRoute(
12 Directory(Directory.current.path),
13 mountPath: '/swagger/',
14 ),
15 );
16
17 // Start the server
18 await pod.start();
19}
Note: The mountPath
parameter must end with a trailing slash.
3. Generate the OpenAPI specification
Run the following command from your project root to generate the OpenAPI specification:
dart run serverpod_swagger:generate
This will create an apispec.json
file in your project root directory.
4. Start your server and access the Swagger UI
Start your Serverpod server and navigate to http://localhost:8082/swagger/
in your browser.
Tip: Make sure to include the trailing slash in the URL. If you navigate to /swagger
(without the trailing slash), you'll be redirected to /swagger/
.
Next Steps
Now that you have Swagger UI integrated with your Serverpod server, you can: