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

FastAPI returns “Error 422: Unprocessable entity” when I send multipart form data with JavaScript Fetch API

The 422 error response body will contain an error message about which field(s) is missing or doesn’t match the expected format. Since you haven’t provided that (please do so), my guess is that the error is triggered due to how you defined the images parameter in your endpoint. Since images is expected to be a … Read more

FastAPI python: How to run a thread in the background?

Option 1 You should start your Thread before calling uvicorn.run, as uvicorn.run is blocking the thread. import time import threading from fastapi import FastAPI import uvicorn app = FastAPI() class BackgroundTasks(threading.Thread): def run(self,*args,**kwargs): while True: print(‘Hello’) time.sleep(5) if __name__ == ‘__main__’: t = BackgroundTasks() t.start() uvicorn.run(app, host=”0.0.0.0″, port=8000) You could also start your thread using … Read more

How to submit HTML form value using FastAPI and Jinja2 Templates?

Option 1 You can have the category name defined as Form parameter in the backend, and submit a POST request from the frontend using an HTML <form>, as described in Method 1 of this answer. app.py from fastapi import FastAPI, Form, Request from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates app = FastAPI() templates = … Read more