Python fastapi simple example

Here’s a simple example of a Python FastAPI application:

from fastapi import FastAPI

app = FastAPI()

@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}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

In this example, we create a FastAPI instance called app. We define two routes: the root route (“/”) and an item route (“/items/{item_id}”). The root route returns a simple JSON response of {“Hello”: “World”}, while the item route takes an item_id as a path parameter and an optional query parameter q. It returns a JSON response containing the provided item_id and q values.

To run the application, you’ll need to install FastAPI and Uvicorn. You can do so using pip:

pip install fastapi uvicorn

Save the code to a file, for example, main.py. Then, you can start the server by running:

uvicorn main:app --reload

The server will start on http://localhost:8000. You can visit http://localhost:8000 in your browser or send requests using tools like cURL or Postman to test the API endpoints.

This is a basic example to get started with FastAPI. You can add more routes, handle request bodies, use models for request validation, and more as your application grows.