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

ParameterTypeDescription
projectRootDirectoryThe root directory where apispec.json is located (typically Directory.current).
mountPathStringThe URL path where Swagger UI is served. Must end with /. Default: /swagger/
customSpecPathString?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:

  1. Spec request — Serves apispec.json from disk on every request (no caching) with Cache-Control: no-store.
  2. UI request — Serves the Swagger UI HTML page (works with both /swagger and /swagger/).
  3. Redirect — Redirects /swagger to /swagger/ for correct relative path resolution.

Method Signature

1
2Future<Response> handleCall(Session session, Request request) async

Usage

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.

Related