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

Option 1 You should start your Thread before calling, as 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(), host=”″, port=8000) You could also start your thread using … 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., /), instead of, for example, /static (or some other path name), as … Read more

How to stream DataFrame using FastAPI without saving the data to csv file?

Approach 1 (recommended) As mentioned in this answer, as well as here and here, when the entire data (a DataFrame in your case) is already loaded into memory, there is no need to use StreamingResponse. StreamingResponse makes sense when you want to transfer real-time data and when you don’t know the size of your output … 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(‘’) or, use the exception_handlers parameter of the FastAPI class like … Read more

How to customise error response for a specific route in FastAPI?

Option 1 If you didn’t mind having the Header showing as Optional in OpenAPI/Swagger UI autodocs, it would be as easy as follows: from fastapi import Header, HTTPException“/”) def some_route(some_custom_header: Optional[str] = Header(None)): if not some_custom_header: raise HTTPException(status_code=401, detail=”Unauthorized”) return {“some-custom-header”: some_custom_header} Option 2 However, since you would like the Header to appear as … Read more

How to return data in JSON format using FastAPI?

The wrong approach If you serialise the object before returning it, using json.dumps() (as shown in your example), for instance: import json @app.get(‘/user’) async def get_user(): return json.dumps(some_dict, indent=4, default=str) the JSON object that is returned will end up being serialised twice, as FastAPI will automatically serialise the return value behind the scenes. Hence, the … Read more

How to access FastAPI backend from a different machine/IP on the same local network?

Make sure that the host flag is set to, when running the server— means all IPv4 addresses on the local machine. If a host has two IP addresses, e.g., and, and the server running on the host listens on, it will be reachable at both of those IPs. For example, … Read more

Download PDF file using pdfkit and FastAPI

Returning FileResponse is solved my problem. Thanks to @Paul H and @clmno Below codes are working example of returning pdf file to download with FastApi. from typing import Optional from fastapi import FastAPI from starlette.responses import FileResponse import pdfkit app = FastAPI() config = pdfkit.configuration(wkhtmltopdf=r”C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe”) @app.get(“/”) def read_root(): pdfkit.from_url(“”,”file.pdf”, configuration=config) return FileResponse( “file.pdf”, media_type=”application/pdf”, … Read more