Contents

Starlette Routing Examples

0

Starlette routing can be composed in many different ways. Here is a simple example from Starlette’s documentation.

# Ref: https://www.starlette.io/routing/
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route


async def homepage(request):
    return PlainTextResponse("Homepage")


async def about(request):
    return PlainTextResponse("About")


routes = [
    Route("/", endpoint=homepage),
    Route("/about", endpoint=about),
]

app = Starlette(routes=routes)

Submounting routes

In larger starlette applications you need to split views out in seperate python files. starlette.routing.Mount allows you to submount routes.

# Ref: https://www.starlette.io/routing/
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route, Mount

from myproject import users, auth

def homepage(request):
    return PlainTextResponse('Hello, world!')

routes = [
    Route('/', homepage),
    Mount('/users', routes=users.routes),
    Mount('/auth', routes=auth.routes),
]

app = Starlette(routes=routes)

Websocket routes

Websocket routes are created using WebSocketRoute() which can be imported from starlette.routing.

from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route, WebSocketRoute

def homepage(request):
    return PlainTextResponse('Hello, world!')


async def websocket_endpoint(websocket):
    await websocket.accept()
    await websocket.send_text('Hello, websocket!')
    await websocket.close()


async def websocket_alt_endpoint(websocket):
    await websocket.accept()
    await websocket.send_text('Hello, another websocket interface!')
    await websocket.close()


routes = [
    Route('/', homepage),
    WebSocketRoute('/ws', websocket_endpoint)
    WebSocketRoute('/ws2', websocket_alt_endpoint)
]

app = Starlette(routes=routes)

About Starlette

starlette - The little ASGI library that shines.