Fast
Fast
Fast
You can use WSGIMiddleware to mount WSGI applications (like Flask and Django) to
your FastAPI API.
https://fastapi.tiangolo.com/advanced/wsgi/
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 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
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 tip:
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()
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 tip:
You can use Strawberry to build a GraphQL API with FastAPI.
https://fastapi.tiangolo.com/fr/advanced/graphql/#graphql-with-strawberry
import strawberry
@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.
You can use Jinja2 as a template engine to serve HTML responses from your FastAPI
application.
app = FastAPI()
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 tip:
You can use sub-applications when you need two separate OpenAPI schemas and
Swagger UIs.
https://fastapi.tiangolo.com/advanced/sub-applications/
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 tip:
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 tip:
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:
https://fastapi.tiangolo.com/advanced/websockets/
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