-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
39 lines (32 loc) · 1.07 KB
/
Copy pathmain.py
File metadata and controls
39 lines (32 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
# Create a FastAPI app instance
app = FastAPI()
class Item(BaseModel):
text: str # Changed text attribute to be required by removing the "= None" default value
is_done: bool = False
# Items list initializer inst
items = []
# HTTP Get "Hello: World" method path
@app.get("/")
def root():
return {"Hello": "World"}
# HTTP Post "item" method path
# Problem 1: The path should start with a slash: @app.post("/items").
# Enhanced with BaseModel
@app.post("/items")
def create_item(item: Item):
items.append(item)
return item
# HTTP Get item by ID/Index method path (v1.1)
# Enhanced with BaseModel
@app.get("/items/{item_id}", response_model=list[Item])
def get_item(item_id: int) -> Item:
if item_id < len(items):
return items[item_id]
else:
raise HTTPException(status_code=404, detail=f"Item {item_id} not found")
# this endpoint uses a query parameter 'limit'
@app.get("/items", response_model=list[Item])
def list_items(limit: int = 10):
return items[0:limit]