Skip to content

Commit 9960428

Browse files
committed
hw3
1 parent 2135277 commit 9960428

File tree

1 file changed

+37
-3
lines changed

1 file changed

+37
-3
lines changed

main.py

+37-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from fastapi import FastAPI, Path, Query
1+
from fastapi import FastAPI, Path, Query, HTTPException
22
from pydantic import BaseModel
33
from typing import Union
44
from enum import Enum
@@ -18,8 +18,42 @@ async def root():
1818
return {"message": "Hello World"}
1919

2020
@app.put("/items/{item_id}")
21-
async def get_item(item_id: int, item: Item, q: str | None = None):
21+
async def update_item(
22+
item: Item,
23+
item_id: int = Path(..., ge=1, le=1000),
24+
q: str | None = Query(default=None, min_length=3, max_length=50)
25+
):
26+
if q is not None and (len(q) < 3 or len(q) > 50):
27+
raise HTTPException(
28+
status_code=422,
29+
detail="Query 'q' must be between 3 and 50 characters."
30+
)
2231
result = {"item_id": item_id, **item.model_dump()}
2332
if q:
2433
result.update({"q": q})
25-
return result
34+
return result
35+
36+
@app.get("/items/{item_id}")
37+
async def get_item(
38+
item_id: int = Path(..., ge=1, le=1000),
39+
q: str | None = Query(default=None, min_length=3, max_length=50),
40+
sort_order: str = Query(default="asc", regex="^(asc|desc)$")
41+
):
42+
if q is not None and (len(q) < 3 or len(q) > 50):
43+
raise HTTPException(
44+
status_code=422,
45+
detail="Query 'q' must be between 3 and 50 characters."
46+
)
47+
if item_id < 1 or item_id > 1000:
48+
raise HTTPException(
49+
status_code=422,
50+
detail="Item ID must be between 1 and 1000."
51+
)
52+
description = "This is a sample item."
53+
if q:
54+
description = f"This is a sample item that matches the query {q}."
55+
return {
56+
"item_id": item_id,
57+
"description": description,
58+
"sort_order": sort_order
59+
}

0 commit comments

Comments
 (0)