Unit-3 Deployment using FastAPI
Unit-3 Deployment using FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "query": q}
Code Explanation
• FastAPI Initialization: The line app = FastAPI() creates a FastAPI instance. This
instance will handle all the incoming requests and routing.
• GET Request for Root URL:
✓@app.get("/"): This is a decorator that maps the root URL (/) to the
read_root() function.
✓When users visit the root URL (http://127.0.0.1:8000), the function returns
{"message": "Hello World"}.
• Dynamic Path Parameter:
• @app.get("/items/{item_id}"): The part {item_id} allows you to define a
dynamic URL segment.
• The function read_item() takes item_id as an integer parameter and an
optional query string q (e.g., ?q=something).
• The URL http://127.0.0.1:8000/items/42?q=test would return {"item_id": 42,
"query": "test"}.
Visit the Application in a Browser
Running the FastAPI instance:
• Make sure you are running the correct file and the correct app instance.
• If you have named your file main.py, the app should be referenced as main:app
when running uvicorn.
• For example, if your file is named main.py and your FastAPI instance is named
app, the command should be:
Yes (making the same request multiple No (multiple requests may cause different
Idempotency
times results in the same response) outcomes, e.g., multiple resource creation)
app = FastAPI()