Path operations let your web app respond to different requests like getting data, sending new data, updating, or deleting it. They make your app interactive and useful.
Path operations (GET, POST, PUT, DELETE) in FastAPI
from fastapi import FastAPI app = FastAPI() @app.get("/path") async def read_item(): return {"message": "GET request"} @app.post("/path") async def create_item(): return {"message": "POST request"} @app.put("/path") async def update_item(): return {"message": "PUT request"} @app.delete("/path") async def delete_item(): return {"message": "DELETE request"}
Each decorator (@app.get, @app.post, etc.) tells FastAPI which HTTP method to listen for.
Functions below decorators handle the request and return a response.
from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id}
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float @app.post("/items/") async def create_item(item: Item): return {"item_name": item.name, "item_price": item.price}
from fastapi import FastAPI app = FastAPI() @app.put("/items/{item_id}") async def update_item(item_id: int): return {"message": f"Item {item_id} updated"}
from fastapi import FastAPI app = FastAPI() @app.delete("/items/{item_id}") async def delete_item(item_id: int): return {"message": f"Item {item_id} deleted"}
This example shows a simple in-memory store for items. You can create, read, update, and delete items by their ID using the correct HTTP method.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float items_db = {} @app.get("/items/{item_id}") async def read_item(item_id: int): item = items_db.get(item_id) if item: return item return {"error": "Item not found"} @app.post("/items/{item_id}") async def create_item(item_id: int, item: Item): if item_id in items_db: return {"error": "Item already exists"} items_db[item_id] = item.dict() return {"message": "Item created", "item": items_db[item_id]} @app.put("/items/{item_id}") async def update_item(item_id: int, item: Item): if item_id not in items_db: return {"error": "Item not found"} items_db[item_id] = item.dict() return {"message": "Item updated", "item": items_db[item_id]} @app.delete("/items/{item_id}") async def delete_item(item_id: int): if item_id in items_db: del items_db[item_id] return {"message": "Item deleted"} return {"error": "Item not found"}
Use the correct HTTP method to match the action you want (GET to read, POST to create, etc.).
Path parameters like {item_id} let you work with specific items easily.
FastAPI automatically converts and validates data types for you.
Path operations define how your app responds to different HTTP requests.
GET reads data, POST creates, PUT updates, DELETE removes.
Use path parameters to work with specific resources.
Practice
Solution
Step 1: Understand HTTP methods purpose
GET is used to read or retrieve data without modifying it.Step 2: Match method to FastAPI operation
FastAPI uses @app.get() decorator for GET requests to fetch data.Final Answer:
GET -> Option DQuick Check:
GET = Read data [OK]
- Confusing GET with POST which creates data
- Using PUT for reading data
- Thinking DELETE retrieves data
Solution
Step 1: Identify the HTTP method for creating data
POST is used to create new resources in REST APIs.Step 2: Match FastAPI decorator for POST
FastAPI uses @app.post() decorator to handle POST requests.Final Answer:
@app.post('/items/')\ndef create_item(): pass -> Option AQuick Check:
POST = Create data [OK]
- Using @app.get() for creating data
- Confusing PUT with POST
- Using DELETE for creation
from fastapi import FastAPI
app = FastAPI()
items = {5: "old value"}
@app.put('/items/{item_id}')
async def update_item(item_id: int):
items[item_id] = "new value"
return items[item_id]Solution
Step 1: Understand the PUT operation code
The function updates the dictionary value for the given item_id to "new value".Step 2: Check the returned value
The function returns the updated value, which is "new value".Final Answer:
"new value" -> Option AQuick Check:
PUT updates and returns new value [OK]
- Expecting old value after update
- Thinking KeyError occurs without check
- Assuming None is returned
from fastapi import FastAPI
app = FastAPI()
items = {1: "apple", 2: "banana"}
@app.delete('/items/{item_id}')
async def delete_item(item_id: int):
del items[item_id]
return {"message": "Item deleted"}Solution
Step 1: Analyze the delete operation
The code deletes an item by key without verifying if the key exists in the dictionary.Step 2: Understand possible runtime error
If the item_id does not exist, del will raise a KeyError causing a server error.Final Answer:
Deleting item without checking if it exists -> Option CQuick Check:
Delete needs existence check [OK]
- Assuming item always exists
- Ignoring KeyError on delete
- Thinking async is wrong here
Solution
Step 1: Match HTTP methods to CRUD operations
GET retrieves, POST creates, PUT updates, DELETE removes resources.Step 2: Ensure safe update and delete
Update and delete should check if the user exists to avoid errors.Final Answer:
Use @app.get to retrieve, @app.post to create, @app.put to update with existence check, and @app.delete to delete with existence check -> Option BQuick Check:
Correct HTTP methods with safety checks [OK]
- Skipping existence checks causing errors
- Using wrong HTTP methods for actions
- Trying to do all actions with one method
Ready to prove it?
Pass the test and this pattern moves unknown
