Complete the code to create a GET path operation that returns a welcome message.
from fastapi import FastAPI app = FastAPI() @app.[1]("/") async def read_root(): return {"message": "Welcome to FastAPI!"}
The @app.get decorator defines a GET path operation, which is used to retrieve data.
Complete the code to create a POST path operation that accepts an item name and returns it.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str @app.[1]("/items/") async def create_item(item: Item): return {"item_name": item.name}
The @app.post decorator defines a POST path operation, which is used to create new data.
Fix the error in the code to update an item using PUT method.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str @app.[1]("/items/{item_id}") async def update_item(item_id: int, item: Item): return {"item_id": item_id, "updated_name": item.name}
The @app.put decorator is used for updating existing data, which fits the update operation.
Fill both blanks to create a DELETE path operation that deletes an item by its ID.
from fastapi import FastAPI app = FastAPI() @app.[1]("/items/[2]") async def delete_item(item_id: int): return {"message": f"Item {item_id} deleted"}
The @app.delete decorator defines a DELETE path operation. The path must include {item_id} to capture the item ID from the URL.
Fill all three blanks to create a PUT path operation that updates an item and returns its ID and new name.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str @app.[1]("/items/[2]") async def update_item([3]: int, item: Item): return {"item_id": [3], "new_name": item.name}
The @app.put decorator is for updating. The path parameter and function argument must be named item_id to match the URL.