swaggerui

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package swaggerui serves the Swagger UI of an eventhandler.Router's OpenAPI document: Powertools for AWS Lambda (Python)'s enable_swagger.

app := eventhandler.New()
// ... routes ...
swaggerui.Enable(app)

GET /swagger answers the page, ?format=json the document and ?format=oauth2-redirect the OAuth2 redirect page of the UI. The document targets the base path of the API (the API Gateway stage), so that "Try it out" works behind a stage URL.

The page inlines Swagger UI 5.31.0, the version Powertools Python bundles, embedded in this package (about 1.7 MB, so only binaries that import the package carry it). WithBaseURL, WithCSSURL and WithJSURL link the assets from elsewhere instead. Swagger UI is Copyright SmartBear Software Inc., licensed under the Apache License 2.0: see assets/LICENSE, assets/NOTICE and, for the libraries the bundle includes, assets/swagger-ui-bundle.js.LICENSE.txt.

Options

  • WithPath: where the UI is served (default /swagger).
  • WithBaseURL, WithCSSURL, WithJSURL: link the assets instead of inlining them (Python's swagger_base_url).
  • WithPersistAuthorization: keep the authorization across reloads.
  • WithOAuth2: the OAuth2 configuration of the UI (a client secret needs POWERTOOLS_DEV, since every visitor sees it).
  • WithMiddlewares: protect the route, which is public otherwise.
  • WithCompression: gzip the page.
  • WithOpenAPI: adjust the document (title, servers...).
  • WithDocument: serve another document, such as a merge of several functions' documents (Python's configure_openapi_merge).

Environment variables

POWERTOOLS_DEV allows an OAuth2 client secret.

Index

Examples

Constants

View Source
const DefaultPath = "/swagger"

DefaultPath is where the Swagger UI is served.

View Source
const Version = "5.31.0"

Version is the version of the embedded Swagger UI, the one Powertools Python 3.35.0 bundles.

Variables

View Source
var ErrClientSecret = errors.New("swaggerui: cannot use an OAuth2 client secret without POWERTOOLS_DEV")

ErrClientSecret reports an OAuth2 client secret outside development mode: the secret would be served to every visitor of the page.

Functions

func Enable

func Enable(r *eventhandler.Router, opts ...Option)

Enable serves the Swagger UI of r's OpenAPI document at GET /swagger: Python's enable_swagger. The route is not part of the document. The same path answers ?format=json with the document and ?format=oauth2-redirect with the OAuth2 redirect page.

It panics with ErrClientSecret when the OAuth2 configuration has a client secret and POWERTOOLS_DEV is off, as Python refuses it.

Example
package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/aws/aws-lambda-go/events"

	"github.com/alessandrolattao/powertools-lambda-go/eventhandler"
	"github.com/alessandrolattao/powertools-lambda-go/eventhandler/swaggerui"
)

func main() {
	app := eventhandler.New(eventhandler.WithOpenAPI(eventhandler.OpenAPIConfig{Title: "Todos"}))
	eventhandler.Get(app, "/todos", func(context.Context, struct{}) ([]string, error) { return nil, nil })
	swaggerui.Enable(app, swaggerui.WithCompression())

	handler := eventhandler.APIGatewayREST(app)
	page, err := handler(context.Background(), events.APIGatewayProxyRequest{HTTPMethod: "GET", Path: "/swagger"})
	if err != nil {
		panic(err)
	}
	doc, err := handler(context.Background(), events.APIGatewayProxyRequest{
		HTTPMethod: "GET", Path: "/swagger", QueryStringParameters: map[string]string{"format": "json"},
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(page.StatusCode, page.MultiValueHeaders["Content-Type"])
	fmt.Println(strings.Contains(doc.Body, `"title": "Todos"`))
}
Output:
200 [text/html]
true

func Handler

func Handler(r *eventhandler.Router, opts ...Option) http.Handler

Handler returns the handler of the Swagger UI page of r's document, for routers that mount it themselves. Enable registers it.

Types

type OAuth2Config

type OAuth2Config struct {
	// ClientID is the OAuth2 client id.
	ClientID string `json:"clientId,omitempty"`
	// ClientSecret is only allowed with POWERTOOLS_DEV on: it is visible to
	// anyone who loads the page.
	ClientSecret string `json:"clientSecret,omitempty"`
	Realm        string `json:"realm,omitempty"`
	// AppName is the name of the OAuth2 application (required).
	AppName                                   string            `json:"appName"`
	Scopes                                    []string          `json:"scopes,omitempty"`
	AdditionalQueryStringParams               map[string]string `json:"additionalQueryStringParams,omitempty"`
	UseBasicAuthenticationWithAccessCodeGrant bool              `json:"useBasicAuthenticationWithAccessCodeGrant,omitzero"`
	UsePkceWithAuthorizationCodeGrant         bool              `json:"usePkceWithAuthorizationCodeGrant,omitzero"`
}

OAuth2Config configures the OAuth2 authorization of the Swagger UI (ui.initOAuth): Python's OAuth2Config.

type Option

type Option func(*config)

Option configures the Swagger UI.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL links the Swagger UI assets from baseURL ({baseURL}/swagger-ui-bundle.min.js and {baseURL}/swagger-ui.min.css) instead of inlining the embedded ones: Python's swagger_base_url, for a lighter page served from a CDN or a bucket.

func WithCSSURL

func WithCSSURL(url string) Option

WithCSSURL links the stylesheet from url.

func WithCompression

func WithCompression() Option

WithCompression gzips the page (about 1.7 MB with the inlined assets) for clients that accept it.

func WithDocument

func WithDocument(doc func(r *http.Request) ([]byte, error)) Option

WithDocument serves the document doc returns instead of the router's: a merged document of several functions (see eventhandler.MergeOpenAPI), Python's configure_openapi_merge.

func WithJSURL

func WithJSURL(url string) Option

WithJSURL links the Swagger UI bundle from url.

func WithMiddlewares

func WithMiddlewares(middlewares ...eventhandler.Middleware) Option

WithMiddlewares runs middlewares on the Swagger UI route, to protect it: the UI is public otherwise.

func WithOAuth2

func WithOAuth2(cfg OAuth2Config) Option

WithOAuth2 configures the OAuth2 authorization of the UI.

func WithOpenAPI

func WithOpenAPI(opts ...eventhandler.OpenAPIOption) Option

WithOpenAPI adjusts the document the UI shows, over the router's configuration. Without servers among them, the UI targets the base path of the API (the API Gateway stage), so that "Try it out" works.

func WithPath

func WithPath(path string) Option

WithPath serves the UI at path instead of DefaultPath.

func WithPersistAuthorization

func WithPersistAuthorization() Option

WithPersistAuthorization keeps the authorization the user entered across page reloads.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL