create a fastapi app in python

To create a FastAPI app in Python, follow these steps:

  1. Install FastAPI using pip: pip install fastapi
  2. Install uvicorn (optional but recommended for production use): pip install uvicorn
  3. Create a new Python file and import the necessary packages:
    main.py
    from fastapi import FastAPI
    app = FastAPI()  # Create an instance of the FastAPI class
    
    87 chars
    3 lines
  4. Define the route functions for your app:
    main.py
    @app.get("/")
    def read_root():
        return {"Hello": "World"}
    
    @app.get("/items/{item_id}")
    def read_item(item_id: int, q: str = None):
        return {"item_id": item_id, "q": q}
    
    175 chars
    8 lines

In this example, we define two routes: one for the root path ("/") and one for a dynamic path that takes an item_id parameter.

  1. Run your app using uvicorn:
    main.py
    if __name__ == "__main__":
        uvicorn.run(app, host="0.0.0.0", port=8000)
    
    75 chars
    3 lines
    By default, this will run your app on http://localhost:8000.

That's it! You've created a simple FastAPI app in Python. Of course, this is just the beginning - you can explore FastAPI's many features to build more complex and sophisticated apps.

gistlibby LogSnag