Search code examples
pythonmultiprocessingfastapiuvicorn

Python FastAPI putting everything in main()


In Python, I want to be able to write all my application methods in def main() and lastly just run the if __name__, but this way the FastAPI Swagger UI gives an error:

No operations defined in spec!

Basically, my code is something like this:

from fastapi import FastAPI
app = FastAPI()

def main():
    @app.get("/fast")
    async def fast(target: str, input_time: float):
        return (target, input_time)

if __name__ == '__main__':
    main()

Or just simply:

from fastapi import FastAPI
app = FastAPI()

if __name__ == '__main__':
    @app.get("/fast")
    async def fast(target: str, input_time: float):
        return (target, input_time)

Solution

  • Try like this

    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/fast")
    async def fast(target: str, input_time: float):
        return (target, input_time)
    
    

    Now run like this

    uvicorn file_name:app --reload