Skip to content

Instantly share code, notes, and snippets.

William Hayes wshayes

Block or report user

Report or block wshayes

Hide content and notifications from this user.

Learn more about blocking users

Contact Support about this user’s behavior.

Learn more about reporting abuse

Report abuse
View GitHub Profile
wshayes /
Created Aug 2, 2019
[Pydantic subclassing] camelcasing aliases and json dumps #fastapi #pydantic
# @Rehket for what it's worth, I recommend subclassing BaseModel and using that as the root for all of your API models (to reduce code repetition). For example, I use a base class that mostly looks like this:
import re
from functools import partial
from typing import Any, Dict
from fastapi.encoders import jsonable_encoder
from pydantic import BaseConfig, BaseModel
wshayes /
Created Jul 24, 2019
[FastAPI overriding response example] #fastapi
import json
import typing
from starlette.responses import Response
class PrettyJSONResponse(Response):
media_type = "application/json"
wshayes / logging.yml
Created Jul 1, 2019
[Logging tip] #fastapi #python
View logging.yml
version: 1
disable_existing_loggers: False
format: "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s"
class: logging.StreamHandler
level: DEBUG
formatter: simple
wshayes /
Last active Jun 25, 2019
[clean_nulls function] #fastapi #python
import boltons.iterutils
# Note that in FastAPI you can use
# if you have instantiated a Pydantic model and not altered the defaults - the response_model_skip_defaults
# will remove all defaults (including non-None or empty string - any default will be removed.
def clean_nulls(item):
"""Clean null values in responses
wshayes /
Created Jun 24, 2019
[Editable dev env for multiple python libs] #fastapi #python
# Original:
# Setup dev environment
# Setup fully editable stack for:
# proxmox-slack-bot
# fastapi
# starlette
# pydantic
wshayes /
Created Jun 20, 2019
[catch 422 for logging] #fastapi
# euri10 @euri10 15:28
async def logmy422(request, call_next):
response = await call_next(request)
if response.status_code == 422:
logger.debug("that failed")
logger.debug([i async for i in response.body_iterator])
return response
wshayes /
Created Jun 20, 2019
[Testclient example for FastAPI] #fastapi
# From: euri10 @euri10 Jun 19 10:42
@pytest.mark.parametrize("user, expected_status_code", data)
def test_update_user(client, another_user, user, expected_status_code):
url = app.url_path_for("enable")
response = client.patch(url, params={"email":})
assert response.status_code == 401
# client is a small fixture but ymmv:
wshayes / comments
Last active Jun 14, 2019 — forked from dmontagu/
[FastAPI app with response shape wrapping] #fastapi
View comments
From FastAPI Gitter:
dmontagu @dmontagu 00:14
@wshayes @intrepidOlivia here is a fully self-contained working implementation of a wrapped response
you can set context data and errors on the starlette Request and they get added to the response at the end
(@intrepidOlivia if you save the contents of that gist to it should be possible to run via uvicorn main:app --reload)
if the endpoint failed in an expected way and you want to return a StandardResponse with no data field, you provide the type of StandardResponse you want to return instead of an instance
wshayes /
Created Jun 8, 2019
[FastAPI Websocket Example #2] #fastapi
from typing import List
from fastapi import FastAPI
from starlette.responses import HTMLResponse
from starlette.websockets import WebSocket, WebSocketDisconnect
app = FastAPI()
wshayes /
Created May 31, 2019
[FastAPI code samples] #fastapi
# Detecting multiple request methods
@app.api_route(methods=["PATCH", "POST"])
async def profile(request: Request, api_key: str = Depends(get_api_key)):
if request.method == 'POST':
You can’t perform that action at this time.