FastAPI as a Windows service

Viewed 6143

I am trying to run FastAPI as a windows service.Couldn't find any documentation or any article to run Uvicorn as a Window's service. I tried using NSSM as well but my windows service stops.

1 Answers

I managed to run FastAPI with uvicorn as a Windows Service using NSSM.

I had to deploy uvicorn programatically, basically run uvicorn directly from your Python script, then create and install a custom service with NSSM.

Here's a small example based on FastAPI's example, but instead of running it with uvicorn main:app --reload from the command line, you add uvicorn.run(app, **config) with your own config.

from fastapi import FastAPI
import uvicorn

app = FastAPI()


@app.get("/")
def read_root():
    return {"Hello": "World"}

if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=5000, log_level="info")

Then you can install it with NSSM using the standard nssm install command

nssm.exe install "FastAPIWindowsService" "C:\Scripts\FastAPIWindowsService\venv\Scripts\python.exe" "C:\Scripts\FastAPIWindowsService\src\main.py"

Change your service name, the path of your python.exe, and the path of your script accordingly. Your service should appear in the Windows Services Manager when installed.

Hope this helps, and works for you!

Related