Posts tagged: fastapi

All posts with the tag "fastapi"

29 posts latest post 2024-12-26
Publishing rhythm
Dec 2024 | 2 posts
- Great list of 4 tips for running fastapi applications. Keep routes small # [2] Fat routers with all of the logic built in makes them hard to test, hard to refactor, causes lots of duplication, and makes it hard to reuse the business logic code later in something like a cli application. Deploy Early # [3] I really like this advice! He reccommends deploying as early as you can get a healthcheck live in your application. I’ve found too many times developers build something that is really hard, or impossible to deploy, when if they had tried to deploy early they would have spotted some easy to fix issues. This is less important if you are building out of a template that your team commonly deploys from, but very important with new patterns. https://youtu.be/XlnmN4BfCxw?si=ks1wvmgDyoQLgrv2&t=1093 [4] Note This post is a thought [5]. It’s a short note that I make about someone else’s content online #thoughts References: [1]: /fastapi/ [2]: #keep-routes-small [3]: #deploy-early [4]: https://youtu.be/XlnmN4BfCxw?si=ks1wvmgDyoQLgrv2&t=1093 [5]: /thoughts/
Add a healthcheck to your FastAPI app | Nic Payne I'm building a few FastAPI apps to throw in docker and run on my homelab... I wanted to add healthchecks and here's a simple way to do it Make sure to pype.dev [1] Nice example of adding a healthcheck to fastapi [2], and integrating it with docker. Don’t forget to include curl in the install, nice touch. Note This post is a thought [3]. It’s a short note that I make about someone else’s content online #thoughts References: [1]: https://pype.dev/add-a-healthcheck-to-your-fastapi-app [2]: /fastapi/ [3]: /thoughts/
FastHX - FastHX volfpeter.github.io [1] Very interesting approach to htmx [2] and fast api. It uses separate decorators for returning template partials and json that can be stacked to include both options on a single route. The templates are explicitly set in the decorator. Separate decorators are used for full page and partial pages. I don’t see an example of full and partial pages being combined. I think the demo app must be behaving in a spa like fashion where it does not get all of the data when it calls index and index will ask for user-list. Definitely going to keep my eye on this project and ponder on it. from fastapi import FastAPI from fastapi.templating import Jinja2Templates from fasthx import Jinja from pydantic import BaseModel # Pydantic model of the data the example API is using. class User(BaseModel): first_name: str last_name: str # Create the app. app = FastAPI() # Create a FastAPI Jinja2Templates instance and use it to create a # FastHX Jinja instance that will serve as your decorator. jinja = Jinja(Jinja2Templates("templates")) @app.get("/") @jinja.page("index.html") def index() -> None: ... @app.get("/user-list") @jinja.hx("user-list.html") async...
FastHX - FastHX volfpeter.github.io [1] Very interesting approach to htmx [2] and fast api. It uses separate decorators for returning template partials and json that can be stacked to include both options on a single route. The templates are explicitly set in the decorator. Separate decorators are used for full page and partial pages. I don’t see an example of full and partial pages being combined. I think the demo app must be behaving in a spa like fashion where it does not get all of the data when it calls index and index will ask for user-list. Definitely going to keep my eye on this project and ponder on it. from fastapi import FastAPI from fastapi.templating import Jinja2Templates from fasthx import Jinja from pydantic import BaseModel # Pydantic model of the data the example API is using. class User(BaseModel): first_name: str last_name: str # Create the app. app = FastAPI() # Create a FastAPI Jinja2Templates instance and use it to create a # FastHX Jinja instance that will serve as your decorator. jinja = Jinja(Jinja2Templates("templates")) @app.get("/") @jinja.page("index.html") def index() -> None: ... @app.get("/user-list") @jinja.hx("user-list.html") async...
Background Tasks - FastAPI FastAPI framework, high performance, easy to learn, fast to code, ready for production fastapi.tiangolo.com [1] fastapi [2] comes with a concept of background tasks which are functions that can be ran in the background after a function has been ran. This is handy for longer running functions that may take some time and you want to have fast response times. Here is an example from the docs from fastapi import BackgroundTasks, FastAPI app = FastAPI() def write_notification(email: str, message=""): with open("log.txt", mode="w") as email_file: content = f"notification for {email}: {message}" email_file.write(content) @app.post("/send-notification/{email}") async def send_notification(email: str, background_tasks: BackgroundTasks): background_tasks.add_task(write_notification, email, message="some notification") return {"message": "Notification sent in the background"} Note This post is a thought [3]. It’s a short note that I make about someone else’s content online #thoughts References: [1]: https://fastapi.tiangolo.com/tutorial/background-tasks/ [2]: /fastapi/ [3]: /thoughts/
Fields Pydantic Docs · docs.pydantic.dev [1] exclude=True and repr=False is a good pydantic combination for secret attributes such as user passwords, or hashed passwords. exclude keeps it out of model_dumps, and repr keeps it out of the logs. from pydantic import BaseModel, Field class User(BaseModel): name: str = Field(repr=True) age: int = Field(repr=False) user = User(name='John', age=42) print(user) #> name='John' Note This post is a thought [2]. It’s a short note that I make about someone else’s content online #thoughts References: [1]: https://docs.pydantic.dev/2.7/concepts/fields/#field-representation [2]: /thoughts/
Handling Errors - FastAPI FastAPI framework, high performance, easy to learn, fast to code, ready for production fastapi.tiangolo.com [1] This page shows how to customize your fastapi [2] errors. I found this very useful to setup common templates so that I can return the same 404’s both programatically and by default, so it all looks the same to the end user. from fastapi import FastAPI, Request from fastapi.responses import JSONResponse class UnicornException(Exception): def __init__(self, name: str): self.name = name app = FastAPI() @app.exception_handler(UnicornException) async def unicorn_exception_handler(request: Request, exc: UnicornException): return JSONResponse( status_code=418, content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."}, ) @app.get("/unicorns/{name}") async def read_unicorn(name: str): if name == "yolo": raise UnicornException(name=name) return {"unicorn_name": name} --- This post sat in draft for months. I stumbled upon it again and found great success returning good error messages based on user preferences. the default remains json, but if a user requests text/html it will be an html [3] response, and text for ...
![[None]] I’ve been using these decorators to modify the behavior of specific routes. It will do things like 404 admin only routes in a way that looks just like fastapi [1]’s default, or only allow certain roles into the route, or redirect unauthenticated users to login. After listening to yesterday’s syntaxfm I’m now really thinking about middleware and the benefits it might have. middleware would make it easy to apply things like admin to an entire admin router, so you wont forget it on any one admin route. It will look cleaner as the admin checker is only applied once per router, not once per route. import inspect import time from functools import wraps from inspect import signature from fastapi import Request from fastapi.responses import FileResponse, JSONResponse, RedirectResponse from starlette import status from fokais.config import get_config from fokais.models.user import Role config = get_config() admin_routes = [] authenticated_routes = [] not_cached_routes = [] cached_routes = [] def not_found(request): hx_request_header = request.headers.get("hx-request") user_agent = request.headers.get("user-agent", "").lower() if "mozilla" in user_agent or "webkit" i...
![[None]] jinja’s url_for in fastapi [1] does not account for https by default, there is probably a better way, but this is a way that allows me to configure when I use http vs https. @pass_context def https_url_for(context: dict, name: str, **path_params: Any) -> str: """ always convert http to https """ request = context["request"] http_url = request.url_for(name, **path_params) return str(http_url).replace("http", "https", 1) def get_templates(config: BaseSettings) -> Jinja2Templates: templates = Jinja2Templates(directory="templates") templates.env.globals["https_url_for"] = https_url_for ## only use the default url_for for local development, for dev, qa, and prod use https if os.environ.get("ENV") in ["dev", "qa", "prod"]: templates.env.globals["url_for"] = https_url_for console.print("Using HTTPS") else: console.print("Using HTTP") return templates Note This post is a thought [2]. It’s a short note that I make about someone else’s content online #thoughts References: [1]: /fastapi/ [2]: /thoughts/
External Link stackoverflow.com [1] After struggling to get dependencies inside of middleware I learned that you can make global dependencies at the app level. I used this to set the user on every single route of the application without needing Depend on getting the user on each route. from fastapi import Depends, FastAPI, Request def get_db_session(): print("Calling 'get_db_session(...)'") return "Some Value" def get_current_user(session=Depends(get_db_session)): print("Calling 'get_current_user(...)'") return session def recalculate_resources(request: Request, current_user=Depends(get_current_user)): print("calling 'recalculate_resources(...)'") request.state.foo = current_user app = FastAPI(dependencies=[Depends(recalculate_resources)]) @app.get("/") async def root(request: Request): return {"foo_from_dependency": request.state.foo} Note This post is a thought [2]. It’s a short note that I make about someone else’s content online #thoughts References: [1]: https://stackoverflow.com/questions/72243379/fastapi-dependency-inside-middleware#answer-72480781 [2]: /thoughts/
Handling Errors - FastAPI FastAPI framework, high performance, easy to learn, fast to code, ready for production fastapi.tiangolo.com [1] This page shows how to customize your fastapi [2] errors. I found this very useful to setup common templates so that I can return the same 404’s both programatically and by default, so it all looks the same to the end user. from fastapi import FastAPI, Request from fastapi.responses import JSONResponse class UnicornException(Exception): def __init__(self, name: str): self.name = name app = FastAPI() @app.exception_handler(UnicornException) async def unicorn_exception_handler(request: Request, exc: UnicornException): return JSONResponse( status_code=418, content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."}, ) @app.get("/unicorns/{name}") async def read_unicorn(name: str): if name == "yolo": raise UnicornException(name=name) return {"unicorn_name": name} Note This post is a thought [3]. It’s a short note that I make about someone else’s content online #thoughts References: [1]: https://fastapi.tiangolo.com/tutorial/handling-errors/ [2]: /fastapi/ [3]: /thoughts/
logs with FastAPI and Uvicorn · Issue #1508 · fastapi/fastapi Hello, Thanks for FastAPI, easy to use in my Python projects ! However, I have an issue with logs. In my Python project, I use : app = FastAPI() uvicorn.run(app, host="0.0.0.0", port=8000) And when... GitHub · github.com [1] Setting an additional log handler to the uvicorn logger for access logs in fastapi [2] was not straightforward, but This post was very helpful. @app.on_event("startup") async def startup_event(): logger = logging.getLogger("uvicorn.access") handler = logging.StreamHandler() handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")) logger.addHandler(handler) Note This post is a thought [3]. It’s a short note that I make about someone else’s content online #thoughts References: [1]: https://github.com/tiangolo/fastapi/issues/1508 [2]: /fastapi/ [3]: /thoughts/
External Link stackoverflow.com [1] Setting tags in your fastapi endpoints will group them in the docs. You can also set some metadata around the tags to get nice descriptions. Here is a full example from the post. from fastapi import FastAPI tags_metadata = [ {"name": "Get Methods", "description": "One other way around"}, {"name": "Post Methods", "description": "Keep doing this"}, {"name": "Delete Methods", "description": "KILL 'EM ALL"}, {"name": "Put Methods", "description": "Boring"}, ] app = FastAPI(openapi_tags=tags_metadata) @app.delete("/items", tags=["Delete Methods"]) @app.put("/items", tags=["Put Methods"]) @app.post("/items", tags=["Post Methods"]) @app.get("/items", tags=["Get Methods"]) async def handle_items(): return Note This post is a thought [2]. It’s a short note that I make about someone else’s content online #thoughts References: [1]: https://stackoverflow.com/questions/63762387/how-to-group-fastapi-endpoints-in-swagger-ui#answer-63762765 [2]: /thoughts/
Path Operation Advanced Configuration - FastAPI FastAPI framework, high performance, easy to learn, fast to code, ready for production fastapi.tiangolo.com [1] Excluding routes from fastapi docs, can be done from the route configuration using `include_in_schema`. This is handy for routes that are not really api based or duplicates. From the Docs # [2] from fastapi import FastAPI app = FastAPI() @app.get("/items/", include_in_schema=False) async def read_items(): return [{"item_id": "Foo"}] trailing slash # [3] I’ve had better luck just routing both naked and trailing slash routes in fastapi [4]. I’ve had api’s deployed as a subroute to a site rather than a subdomain, and the automatic redirect betweens them tended to always get messed up. This is pretty easy fix for the pain is causes just give vim a yyp, and if you don’t want deuplicates in your docs, ignore one. from fastapi import FastAPI app = FastAPI() @app.get("/items") @app.get("/items/", include_in_schema=False) async def read_items(): return [{"item_id": "Foo"}] favicon.ico # [5] Now you do not need to deploy favicons to your api in any way, it is nice to have it in your browser tab, but more importantly ...
Protect API docs behind authentication? · Issue #364 · fastapi/fastapi Basic Question Does FastAPI provide a method for implementing authentication middleware or similar on the docs themselves (e.g. to protect access to /docs and /redoc)? Additional context My company... GitHub · github.com [1] You can protect your fastapi [2] docs behind auth so that not only can certain roles not run certain routes, but they cannot even see the docs at all. This way no one that shouldn’t be poking around can even discover routes they shouldn’t be using. Here is the soluteion provided by @kennylajara [3] from fastapi import FastAPI from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html from fastapi.openapi.utils import get_openapi import secrets from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import HTTPBasic, HTTPBasicCredentials app = FastAPI( title="FastAPI", version="0.1.0", docs_url=None, redoc_url=None, openapi_url = None, ) security = HTTPBasic() def get_current_username(credentials: HTTPBasicCredentials = Depends(security)): correct_username = secrets.compare_digest(credentials.username, "user") correct_password = secrets...
GitHub - florimondmanca/arel: Lightweight browser hot reload for Python ASGI web apps Lightweight browser hot reload for Python ASGI web apps - florimondmanca/arel GitHub · github.com [1] arel is a “Lightweight browser hot reload for Python ASGI web apps” I just implemented this on my thoughts website using fastapi [2], and it’s incredibly fast and lightweight. There just two lines of js that make a web socket connection back to the backend that watches for changes. When in development mode, this snippet gets injected directly on the page and does a refresh when arel detects a change. const ws = new WebSocket("ws://localhost:5000/hot-reload"); ws.onmessage = () => window.location.reload(); Note This post is a thought [3]. It’s a short note that I make about someone else’s content online #thoughts References: [1]: https://github.com/florimondmanca/arel [2]: /fastapi/ [3]: /thoughts/
main.py [1] python import os import arel from fastapi import FastAPI, Request from fastapi.templating import Jinja2Templates app = FastAPI() templates = Jinja2Templates("templates") if _debug := os.getenv("DEBUG"): hot_reload = arel.HotReload(paths=[arel.Path(".")]) app.add_websocket_route("/hot-reload", route=hot_reload, name="hot-reload") app.add_event_handler("startup", hot_reload.startup) app.add_event_handler("shutdown", hot_reload.shutdown) templates.env.globals["DEBUG"] = _debug templates.env.globals["hot_reload"] = hot_reload @app.get("/") def index(request: Request): return templates.TemplateResponse("index.html", context={"request": request}) # run: # DEBUG=true uvicorn main:app --reload I just discovered arel [2] for hot reloading python applications when content changes from this snippet that implements it for fatapi. On app startup add the /hot-reload routes if in DEBUG mode. import os import arel from fastapi import FastAPI, Request from fastapi.templating import Jinja2Templates app = FastAPI() templates = Jinja2Templates("templates") if _debug := os.getenv("DEBUG"): hot_reload = arel.HotReload(paths=[arel.Path(".")]) app.add_websocket_route("...
Bigger Applications - Multiple Files - FastAPI FastAPI framework, high performance, easy to learn, fast to code, ready for production fastapi.tiangolo.com [1] Fastapi [2] lets you tag your APIRouter’s so that the swagger docs are grouped according to the router. router = APIRouter(tags=['router']) Now all routes in router will appear in the router group in the swagger docs. Note This post is a thought [3]. It’s a short note that I make about someone else’s content online #thoughts References: [1]: https://fastapi.tiangolo.com/tutorial/bigger-applications/#another-module-with-apirouter [2]: /fastapi/ [3]: /thoughts/
Create Models with a Many-to-Many Link - SQLModel SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness. sqlmodel.tiangolo.com [1] Creating many to many relationships with sqlmodel requires a LinkTable Model. The link model will keep track of the linked id’s between each of the models. [2] from typing import List, Optional from sqlmodel import Field, Relationship, Session, SQLModel, create_engine class HeroTeamLink(SQLModel, table=True): team_id: Optional[int] = Field( default=None, foreign_key="team.id", primary_key=True ) hero_id: Optional[int] = Field( default=None, foreign_key="hero.id", primary_key=True ) class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) headquarters: str heroes: List["Hero"] = Relationship(back_populates="teams", link_model=HeroTeamLink) class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) teams: List[Team] = Relationship(back_populates="heroes", link_model=HeroTeamLink) Note This post...