mirror of
https://github.com/fastapi/fastapi.git
synced 2025-12-30 17:50:39 -05:00
* Updated .py files with Optional tag (up to body_nested_models) * Update optionals * docs_src/ all updates, few I was unsure of * Updated markdown files with Optional param * es: Add Optional typing to index.md * Last of markdown files updated with Optional param * Update highlight lines * it: Add Optional typings * README.md: Update with Optional typings * Update more highlight increments * Update highlights * schema-extra-example.md: Update highlights * updating highlighting on website to reflect .py changes * Update highlighting for query-params & response-directly * Address PR comments * Get rid of unnecessary comment * ⏪ Revert Optional in Chinese docs as it probably also requires changes in text * 🎨 Apply format * ⏪ Revert modified example * ♻️ Simplify example in docs * 📝 Update OpenAPI callback example to use Optional * ✨ Add Optional types to tests * 📝 Update docs about query params, default to using Optional * 🎨 Update code examples line highlighting * 📝 Update nested models docs to use "type parameters" instead of "subtypes" * 📝 Add notes about FastAPI usage of None including: = None and = Query(None) and clarify relationship with Optional[str] * 📝 Add note about response_model_by_alias * ♻️ Simplify query param list example * 🔥 Remove test for removed example * ✅ Update test for updated example Co-authored-by: Christopher Nguyen <chrisngyn99@gmail.com> Co-authored-by: yk396 <yk396@cornell.edu> Co-authored-by: Kai Chen <kaichen120@gmail.com>
38 lines
1.0 KiB
Python
38 lines
1.0 KiB
Python
from typing import List, Optional
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.encoders import jsonable_encoder
|
|
from pydantic import BaseModel
|
|
|
|
app = FastAPI()
|
|
|
|
|
|
class Item(BaseModel):
|
|
name: Optional[str] = None
|
|
description: Optional[str] = None
|
|
price: Optional[float] = None
|
|
tax: float = 10.5
|
|
tags: List[str] = []
|
|
|
|
|
|
items = {
|
|
"foo": {"name": "Foo", "price": 50.2},
|
|
"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
|
|
"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
|
|
}
|
|
|
|
|
|
@app.get("/items/{item_id}", response_model=Item)
|
|
async def read_item(item_id: str):
|
|
return items[item_id]
|
|
|
|
|
|
@app.patch("/items/{item_id}", response_model=Item)
|
|
async def update_item(item_id: str, item: Item):
|
|
stored_item_data = items[item_id]
|
|
stored_item_model = Item(**stored_item_data)
|
|
update_data = item.dict(exclude_unset=True)
|
|
updated_item = stored_item_model.copy(update=update_data)
|
|
items[item_id] = jsonable_encoder(updated_item)
|
|
return updated_item
|