Search code examples
pythonwindows-servicesfastapi

FastAPI as a Windows service is running but can't get in 127.0.0.1:5000


So, i was trying to run FastAPI as a windows service. I tried the code witout uvicorn programitically to run in local server. It worked fine. But, with programatically to run as a service it start and run the service but not getting the output in local server with the browser. I took reference from this link

Here is my main.py code

from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional

import uvicorn

app = FastAPI()

fakedb = []

class Course(BaseModel):
    id: int
    name: str
    price: float
    is_early_bird: Optional[bool] = None

@app.get("/")
def read_root():
    return {"greetings": "Welocome to Shubbak"}

@app.get("/courses")
def get_courses():
    return fakedb

@app.get("/courses/{course_id}")
def get_a_course(course_id: int):
    course = course_id - 1
    return fakedb[course]

@app.post("/course")
def add_course(course: Course):
    fakedb.append(course.dict())
    return fakedb[-1]

@app.delete("/courses/{course_id}")
def delete_course(course_id:int):
    fakedb.pop(course_id-1)
    return{"task": "deletion success"}

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

Solution

  • Ok I got the solution.

    Steps:

    1. Install service with nssm from cmd as admin
    2. Insert python.exe path, then main.py(api filename) path and at last put file name main.py in the argument.
    3. After install, start the service and check in the browser.

    Check my gitlab link for details.