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 3.2.3 or higher
  • Dart 3.0.0 or higher
  • A working Serverpod project

Installation

Add the package to your pubspec.yaml file:

pubspec.yaml
1dependencies:
2  serverpod: ^3.2.3
3  serverpod_swagger: ^0.3.0

Then run:

dart pub get

Basic Setup

To add Swagger UI to your Serverpod server, follow these steps:

1. Import the package

main.dart
1import 'dart:io';
2import 'package:serverpod/serverpod.dart';
3import 'package:serverpod_swagger/serverpod_swagger.dart';

2. Add the Swagger UI route to your server

main.dart
1import 'dart:io';
2import 'package:serverpod/serverpod.dart';
3import 'package:serverpod_swagger/serverpod_swagger.dart';
4
5void run(List<String> args) async {
6  final pod = Serverpod(
7    args,
8    Protocol(),
9    Endpoints(),
10  );
11  
12  // Add the Swagger UI route
13  final swaggerRoute = SwaggerUIRoute(Directory.current);
14  pod.webServer.addRoute(swaggerRoute, '/swagger/**');
15  
16  // Start the server
17  await pod.start();
18}

Note: The route pattern /swagger/** is a wildcard that matches all paths starting with /swagger.

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: