SwaggerUIRoute
The SwaggerUIRoute class extends Serverpod's Route class to serve a live-reloading Swagger UI and the apispec.json file.
Constructor
1SwaggerUIRoute(
2 Directory projectRoot, {
3 String mountPath = '/swagger/',
4 String? customSpecPath,
5})Parameters
| Parameter | Type | Description |
|---|---|---|
projectRoot | Directory | The root directory where apispec.json is located (typically Directory.current). |
mountPath | String | The URL path where Swagger UI is served. Must end with /. Default: /swagger/ |
customSpecPath | String? | Override the URL from which Swagger UI loads the API spec. If null, defaults to <mountPath>/apispec.json. |
How It Works
The handleCall method handles three request types:
- Spec request — Serves
apispec.jsonfrom disk on every request (no caching) withCache-Control: no-store. - UI request — Serves the Swagger UI HTML page (works with both
/swaggerand/swagger/). - Redirect — Redirects
/swaggerto/swagger/for correct relative path resolution.
Method Signature
1
2Future<Response> handleCall(Session session, Request request) asyncUsage
Default Setup
server.dart
import 'dart:io';
import 'package:serverpod_swagger/serverpod_swagger.dart';
// Swagger UI at /swagger/ and /swagger
pod.webServer.addRoute(
SwaggerUIRoute(Directory.current),
'/swagger/**',
);
pod.webServer.addRoute(
SwaggerUIRoute(Directory.current),
'/swagger',
);Custom Path with Separate Spec Route
server.dart
// Swagger UI at /docs/, spec at /apispec.json
pod.webServer.addRoute(
SwaggerUIRoute(
Directory.current,
mountPath: '/docs/',
customSpecPath: '/apispec.json',
),
'/docs/**',
);
// Serve apispec.json at root
pod.webServer.addRoute(
ApiSpecRoute(Directory.current),
'/apispec.json',
);Security
The spec URL is JSON-encoded before being injected into the HTML to prevent XSS attacks via crafted customSpecPath values.