1
- from fastapi import FastAPI , Path , Query
1
+ from fastapi import FastAPI , Path , Query , HTTPException
2
2
from pydantic import BaseModel
3
3
from typing import Union
4
4
from enum import Enum
@@ -18,8 +18,42 @@ async def root():
18
18
return {"message" : "Hello World" }
19
19
20
20
@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
+ )
22
31
result = {"item_id" : item_id , ** item .model_dump ()}
23
32
if q :
24
33
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