Birmingham-mumbai


Mixing all types of parameters



tải về 6.62 Mb.
Chế độ xem pdf
trang22/275
Chuyển đổi dữ liệu09.10.2023
Kích6.62 Mb.
#55278
1   ...   18   19   20   21   22   23   24   25   ...   275
Sherwin John Tragura - Building Python Microservices with FastAPI Build secure, scalable, and structured Python microservices from design concepts to infrastructure-Packt Publishing - ebooks Account

Mixing all types of parameters
If you are planning to implement an API service method that declares optional, required, and default 
query and path parameters altogether, you can pursue it because the framework supports it, but 
approach it with some caution due to some standards and rules:
@app.patch("/ch01/account/profile/update/names/
{username}
")
def update_profile_names(
id: UUID

username: str = ''

new_names: Optional[Dict[str, str]] = None
):
if valid_users.get(username) == None:
return {"message": "user does not exist"}
elif new_names == None:
return {"message": "new names are required"}
else:
user = valid_users.get(username)
if user.id == id:


Managing user requests and server response
17
profile = valid_profiles[username]
profile.firstname = new_names['fname']
profile.lastname = new_names['lname']
profile.middle_initial = new_names['mi']
valid_profiles[username] = profile
return {"message": "successfully updated"}
else:
return {"message": "user does not exist"}
The updated version of the preceding 
update_profile_names()
service declares a 
username
path parameter, a 
UUID
id query parameter, and an optional 
Dict[str, str]
type. With mixed 
parameter types, all required parameters should be declared first, followed by default parameters, and 
last in the parameter list should be the optional types. Disregarding this ordering rule will generate 
compiler error.
Request body
request body is a body of data in bytes transmitted from a client to a server through a 
POST

PUT

DELETE
, or 
PATCH
HTTP method operation. In FastAPI, a service must declare a model object to 
represent and capture this request body to be processed for further results.
To implement a model class for the request body, you should first import the 
BaseModel
class 
from the 
pydantic
module. Then, create a subclass of it to utilize all the properties and behavior 
needed by the path operation in capturing the request body. Here are some of the data models used 
by our application:
from pydantic import 

tải về 6.62 Mb.

Chia sẻ với bạn bè của bạn:
1   ...   18   19   20   21   22   23   24   25   ...   275




Cơ sở dữ liệu được bảo vệ bởi bản quyền ©hocday.com 2024
được sử dụng cho việc quản lý

    Quê hương