How to initialise a global object or variable and reuse it in every FastAPI endpoint?

Option 1 You could store the custom class object to the app instance, which allows you to store arbitrary extra state using the generic the app.state attribute, as demonstrated here, as well as here and here. To access the app.state attribute, and subsequently the object, outside the main file (for instance, from a routers submodule … Read more

How to pass URL as a path parameter to a FastAPI route?

Option 1 You could simply use Starlette’s path convertor to capture arbitrary paths. As per Starlette documentation, path returns the rest of the path, including any additional / characters. from fastapi import Request @app.get(‘/{_:path}’) def pred_image(request: Request): return {‘path’: request.url.path[1:]} or @app.get(‘/{full_path:path}’) def pred_image(full_path: str): return {‘path’: full_path} Test using the link below: http://127.0.0.1:8000/https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/zidane.jpg Please … Read more

How to return a custom 404 Not Found page using FastAPI?

Update A more elegant solution would be to use a custom exception handler, passing the status code of the exception you would like to handle, as shown below: from fastapi.responses import RedirectResponse from fastapi.exceptions import HTTPException @app.exception_handler(404) async def not_found_exception_handler(request: Request, exc: HTTPException): return RedirectResponse(‘https://fastapi.tiangolo.com’) or, use the exception_handlers parameter of the FastAPI class like … Read more

How to navigate through FastAPI routes by clicking on HTML button in Jinja2 Templates?

Backend Your /tasks endpoint (i.e., find_all_tasks function) should return a new Jinja2 TemplateResponse with the list of tasks. For instance: @app.get(‘/tasks’) def find_all_tasks(request: Request): tasks = [‘task 1’, ‘task 2’, ‘task 3’] return templates.TemplateResponse(“tasks.html”, {“request”: request, ‘tasks’: tasks}) Frontend 1. Click on the URL to get to the tasks page In index.html, you can use … Read more

How to download a large file using FastAPI?

If you find yield from f being rather slow when using StreamingResponse with file-like objects, for instance: from fastapi import FastAPI from fastapi.responses import StreamingResponse some_file_path=”large-video-file.mp4″ app = FastAPI() @app.get(“https://stackoverflow.com/”) def main(): def iterfile(): with open(some_file_path, mode=”rb”) as f: yield from f return StreamingResponse(iterfile(), media_type=”video/mp4″) you could instead create a generator where you read the … Read more

How to add background tasks when request fails and HTTPException is raised in FastAPI?

The way to do this is to override the HTTPException error handler, and since there is no BackgroundTasks object in the exception_handler, you can add a background task to a response in the way that is described in Starlette documentation (FastAPI is actually Starlette underneath). Example from fastapi import BackgroundTasks, FastAPI, HTTPException, Request from fastapi.responses … Read more

How to create a FastAPI endpoint that can accept either Form or JSON body?

Option 1 You could do that by having a dependency function, where you check the value of the Content-Type request header and parse the body using Starlette’s methods, accordingly. Note that just because a request’s Content-Type header says, for instance, application/json, application/x-www-form-urlencoded or multipart/form-data, doesn’t always mean that this is true, or that the incoming … Read more

How to load a different file than index.html in FastAPI root path?

As per Starlette documentation: StaticFiles Signature: StaticFiles(directory=None, packages=None, check_dir=True) html – Run in HTML mode. Automatically loads index.html for directories if such file exists. In addtion, as shown from the code snippet you provided, you have mounted StaticFiles to the root directory (i.e., “https://stackoverflow.com/”), instead of, for example, /static (or some other path name), as … Read more