Fast

Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 10

astAPI tip:

You can use WSGIMiddleware to mount WSGI applications (like Flask and Django) to
your FastAPI API.

https://fastapi.tiangolo.com/advanced/wsgi/

from fastapi import FastAPI


from fastapi.middleware.wsgi import WSGIMiddleware
from flask import Flask, escape, request

flask_app = Flask(__name__)

@flask_app.route("/")
def flask_main():
        name = request.args.get("name", "World")
        return f"Hello, {escape(name)} from Flask!"

app = FastAPI()

@app.get("/v2")
def read_main():
        return {"message": "Hello World"}

app.mount("/v1", WSGIMiddleware(flask_app))

fastapi
Posted on Twitter on Feb. 24, 2022.

FastAPI - disable OpenAPI docs

FastAPI tip:
You can disable OpenAPI docs by setting openapi_url to an empty string.

https://fastapi.tiangolo.com/advanced/conditional-openapi/#conditional-openapi-from-
settings-and-env-vars

from fastapi import FastAPI


from pydantic import BaseSettings

class Settings(BaseSettings):
        openapi_url: str = ""

settings = Settings()

app = FastAPI(openapi_url=settings.openapi_url)

@app.get("/")
def root():
        return {"message": "Hello World"}

fastapi
Posted on Twitter on Feb. 23, 2022.

FastAPI - custom Request and APIRoute class

FastAPI tip:

You can implement custom Request and APIRoute classes.

https://fastapi.tiangolo.com/advanced/custom-request-and-route/

For example, to manipulate the request body before it's processed by your application👇

import gzip
from typing import Callable, List
from fastapi import Body, FastAPI, Request, Response
from fastapi.routing import APIRoute

class GzipRequest(Request):
        async def body(self) -> bytes:
                if not hasattr(self, "_body"):
                        body = await super().body()
                        if "gzip" in self.headers.getlist("Content-Encoding"):
                                body = gzip.decompress(body)
                        self._body = body
                return self._body

class GzipRoute(APIRoute):
        def get_route_handler(self) -> Callable:
                original_route_handler = super().get_route_handler()

                async def custom_route_handler(request: Request) -> Response:


                        request = GzipRequest(request.scope, request.receive)
                        return await original_route_handler(request)

                return custom_route_handler

app = FastAPI()
app.router.route_class = GzipRoute

@app.post("/sum")
async def sum_numbers(numbers: List[int] = Body(...)):
        return {"sum": sum(numbers)}

fastapi
Posted on Twitter on Feb. 21, 2022.

FastAPI - GraphQL with Strawberry

FastAPI tip:
You can use Strawberry to build a GraphQL API with FastAPI.

https://fastapi.tiangolo.com/fr/advanced/graphql/#graphql-with-strawberry

import strawberry

from fastapi import FastAPI


from strawberry.asgi import GraphQL

@strawberry.type
class User:
        name: str
        age: int

@strawberry.type
class Query:
        @strawberry.field
        def user(self) -> User:
                return User(name="Patrick", age=100)

schema = strawberry.Schema(query=Query)

graphql_app = GraphQL(schema)

app = FastAPI()
app.add_route("/graphql", graphql_app)
app.add_websocket_route("/graphql", graphql_app)

fastapi
Posted on Twitter on Feb. 20, 2022.

FastAPI - Templates with Jinja2


FastAPI tip:

You can use Jinja2 as a template engine to serve HTML responses from your FastAPI
application.

from fastapi import FastAPI, Request


from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")

templates = Jinja2Templates(directory="templates")

@app.get("/items/{id}", response_class=HTMLResponse)
async def read_item(request: Request, id: str):
        return templates.TemplateResponse("item.html", {"request": request, "id": id})

fastapi
Posted on Twitter on Feb. 19, 2022.

FastAPI Sub Applications

FastAPI tip:

You can use sub-applications when you need two separate OpenAPI schemas and
Swagger UIs.

https://fastapi.tiangolo.com/advanced/sub-applications/

You can mount one or many sub-applications.


👇

from fastapi import FastAPI

app = FastAPI()

@app.get("/app")
def read_main():
        return {"message": "Hello World from main app"}

subapi = FastAPI()

@subapi.get("/sub")
def read_sub():
        return {"message": "Hello World from sub API"}

app.mount("/subapi", subapi)

fastapi
Posted on Twitter on Feb. 18, 2022.

FastAPI shutdown events

FastAPI tip:

You can register functions to run before the application shutdown


using @app.on_event("shutdown").

https://fastapi.tiangolo.com/advanced/events/#shutdown-event

For example. to send a message to an SNS topic where you track your app health 👇

import boto3
from fastapi import FastAPI
app = FastAPI()

@app.on_event("shutdown")
def publish_message():
        client = boto3.client('sns')
        client.publish(
                TopicArn='arn:aws:sns:us-east-1:12345678910112:application-health',
                Message='Application is shutting down',
    )

@app.get("/ping")
async def ping():
        return {"message": "pong"}

fastapi
Posted on Twitter on Feb. 17, 2022.

FastAPI startup events

FastAPI tip:

You can register functions to run before the application start


using @app.on_event("startup").

https://fastapi.tiangolo.com/advanced/events/#startup-event

For example, to send a message to an AWS SNS topic where you track your app health:

import boto3
from fastapi import FastAPI

app = FastAPI()
@app.on_event("startup")
def publish_message():
        client = boto3.client('sns')
        client.publish(
                TopicArn='arn:aws:sns:us-east-1:12345678910112:application-health',
                Message='Application is starting',
    )

@app.get("/ping")
async def ping():
        return {"message": "pong"}

fastapi
Posted on Twitter on Feb. 16, 2022.

FastAPI WebSockets

FastAPI tip:

You can easily add WebSockets to your app with @app.websocket().

https://fastapi.tiangolo.com/advanced/websockets/

from fastapi import FastAPI, WebSocket


from fastapi.responses import HTMLResponse

app = FastAPI()

html = """
<!DOCTYPE html>
<html>
        <head>
                <title>Chat</title>
        </head>
        <body>
                <h1>WebSocket Chat</h1>
                <form action="" onsubmit="sendMessage(event)">
                        <input type="text" id="messageText" autocomplete="off"/>
                        <button>Send</button>
                </form>
                <ul id='messages'>
                </ul>
                <script>
                        var ws = new WebSocket("ws://localhost:8000/ws");
                        ws.onmessage = function(event) {
                                var messages = document.getElementById('messages')
                                var message = document.createElement('li')
                                var content = document.createTextNode(event.data)
                                message.appendChild(content)
                                messages.appendChild(message)
                        };
                        function sendMessage(event) {
                                var input = document.getElementById("messageText")
                                ws.send(input.value)
                                input.value = ''
                                event.preventDefault()
            }
                </script>
        </body>
</html>
"""

@app.get("/")
async def get():
        return HTMLResponse(html)

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
        await websocket.accept()
        while True:
                data = await websocket.receive_text()
                await websocket.send_text(f"Message text was: {data}")

fastapi
Posted on Twitter on Feb. 15, 2022.
FastAPI - Using alias parameters to map fields from
request to view arguments

You might also like