Skip to content

Commit 57e5249

Browse files
author
Dattatraya Tembare
committed
FastAPI post request and input data validation.
1 parent e4e0277 commit 57e5249

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed

README.md

+13
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,15 @@
11
# python-fastapi
22
Python FastAPI examples
3+
4+
**Pydantic:**
5+
6+
Data validation and settings management using python type annotations.
7+
8+
pydantic enforces type hints at runtime, and provides user friendly errors when data is invalid.
9+
10+
Define how data should be in pure, canonical python; validate it with pydantic.
11+
12+
**OpenAPI/Swagger UI:**
13+
14+
A document (or set of documents) that defines or describes an API. An OpenAPI definition uses and conforms
15+
to the OpenAPI Specification.

data_validation_query_path.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import uvicorn
2+
from fastapi import FastAPI, Query, Path
3+
4+
app = FastAPI(debug=True)
5+
item_id: str
6+
7+
8+
@app.get("/items/")
9+
async def read_items(item_id: str = Query(..., min_length=2, max_length=10, regex="^Item\d{1,6}")):
10+
"""
11+
Validate query string parameter values
12+
:param item_id:
13+
:return:
14+
"""
15+
results = {"items": [{"item_id": "Pen"}, {"item_id": "Pencil"}]}
16+
results.update({"New Item": item_id})
17+
return {"item": item_id}
18+
19+
20+
@app.get("/items/{item_id}")
21+
async def get_items(item_id: int = Path(..., le=10, ge=2, title="Item Id")):
22+
"""
23+
Validate Path parameter values.
24+
:param item_id:
25+
:return:
26+
"""
27+
return {"item_id": item_id}
28+
29+
30+
if __name__ == "__main__":
31+
uvicorn.run(app, host="127.0.0.1", port=8000)

post_request_example.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import uvicorn
2+
from fastapi import FastAPI
3+
from pydantic import BaseModel
4+
5+
app = FastAPI(debug=True)
6+
7+
8+
class Item(BaseModel):
9+
name: str
10+
description: str = None
11+
price: float
12+
tax: float = None
13+
14+
15+
@app.post("/items/")
16+
async def create_item(item: Item):
17+
item_dict = item.dict()
18+
if item.tax:
19+
total = item.price + item.tax
20+
item_dict.update({"TotalAmount": total})
21+
return item_dict
22+
23+
24+
if __name__ == "__main__":
25+
uvicorn.run(app, host="127.0.0.1", port=8000)

0 commit comments

Comments
 (0)