Skip to main content

starlette-swagger

requirements:

  • starlette_openapi
  • starlette_pydantic

usage:

from typing import Optional
from starlette.routing import Route
from starlette.applications import Starlette
from pydantic import BaseModel, constr
from starlette_pydantic import PydanticEndpoint, BaseForm
from starlette_openapi import OpenApi
from starlette_swagger import SwaggerUI
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.middleware import Middleware
from starlette.authentication import (
    AuthenticationBackend, AuthenticationError, SimpleUser, UnauthenticatedUser,
    AuthCredentials
)
from starlette_authentication.decorators import requires, token_url
import base64
import binascii


class RequestBody(BaseModel):
    name: int


class ResponseBody(BaseModel):
    age: int


class AuthForm(BaseForm):
    grant_type: str
    username: constr(max_length=64, min_length=8)
    password: constr(max_length=64, min_length=8)


class AuthResponse(BaseModel):
    access_token: str
    refresh_token: Optional[str]
    token_type: str


class BearerAuthBackend(AuthenticationBackend):
    async def authenticate(self, request):
        if "Authorization" not in request.headers:
            return

        auth = request.headers["Authorization"]
        try:
            scheme, credentials = auth.split()
            if scheme.lower() != 'bearer':
                return
            decoded = base64.b64decode(credentials).decode("ascii")
        except (ValueError, UnicodeDecodeError, binascii.Error) as exc:
            raise AuthenticationError('Invalid basic auth credentials')

        username, _, password = decoded.partition(":")
        # TODO: You'd want to verify the username and password here.
        return AuthCredentials(["authenticated"]), SimpleUser(username)


class Auth(PydanticEndpoint):
    tags = ["authentication"]

    @staticmethod
    @token_url
    async def post(request, form: AuthForm) -> AuthResponse:
        return AuthResponse(access_token="access token",
                            refresh_token="refresh token",
                            token_type="Bearer")


class UserDetail(PydanticEndpoint):
    tags = ["user detail"]

    @staticmethod
    @requires('authenticated', status_code=401)
    async def get(request, username: str = None, page: Optional[str] = None) -> ResponseBody:
        return ResponseBody(age=11)


class User(PydanticEndpoint):
    tags = ["user"]

    @staticmethod
    async def post(request, body: RequestBody) -> ResponseBody:
        return ResponseBody(age=21)


routes = [
    Route("/auth", Auth),
    Route("/user", User),
    Route("/user/{username}", UserDetail),
]

middleware = [
    Middleware(AuthenticationMiddleware, backend=BearerAuthBackend())
]

app = Starlette(routes=routes, middleware=middleware)
openapi = OpenApi(app, title="Demo", description="swagger ui demo.")
SwaggerUI(app, openapi)

if __name__ == "__main__":
    import uvicorn

    uvicorn.run("test.main:app", host="0.0.0.0", port=8000, reload=True, debug=True)

docs url: http://IP:PORT/docs

Release files for starlette-swagger 0.13

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for starlette-swagger 0.13
File Size Uploaded
starlette_swagger-0.13.tar.gz 342.4 kB Details

Release files / starlette_swagger-0.13.tar.gz

Download URL starlette_swagger-0.13.tar.gz
Size 342.4 kB
Tags Source
SHA-256 checksum
How to use checksums
70284c12b490609fac71d73454bf7ce8c90375aaae912ba780e7ba2ff160cba1
BLAKE2b-256 checksum
How to use checksums
1d6de301bbbd9f6cd19ad72ec097423fab2ff323b1f788f8f6bc7094ed21f775
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/47.1.0 requests-toolbelt/0.9.1 tqdm/4.58.0 CPython/3.8.5

Release history Release notifications | RSS feed

This release

0.13 This release

1 release file

0.12

1 release file

0.11

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page