Designing
and implementing REST APIs
7
if valid_users.get(username) == None:
return {"message": "user does not exist"}
else:
user = valid_users.get(username)
if checkpw(password.encode(),
user.passphrase.encode()):
return user
else:
return {"message": "invalid user"}
This
login service uses bcrypt’s
checkpw()
function to check whether the password of the user is
valid. Conversely, the
sign-up service, which also requires user credentials
from the client in the form
of request parameters,
is created as a
POST
API method:
@app.post("/ch01/login/signup")
def
signup
(uname: str, passwd: str):
if (uname == None and passwd == None):
return {"message": "invalid user"}
elif not valid_users.get(uname) == None:
return {"message": "user exists"}
else:
user = User(username=uname, password=passwd)
pending_users[uname] = user
return user
Among the
profile management services, the following
update_profile()
service serves as a
PUT
API service, which requires the user to use an entirely new model object for profile information
replacement and the client’s username to serve as the key:
@app.put("/ch01/account/profile/update/{username}")
def
update_profile
(username: str, id: UUID,
new_profile: UserProfile
):
if valid_users.get(username) == None:
return {"message": "user does not exist"}
else:
user = valid_users.get(username)
if user.id == id:
valid_profiles[username] = new_profile
Setting Up FastAPI for Starters
8
return {"message": "successfully updated"}
else:
return {"message": "user does not exist"}
Not all services
that carry out updates are
PUT
API methods, such as the following
update_
profile_name()
service, which only requires the user to submit a new first name, last name, and
middle initial for partial replacement of a client’s profile. This
HTTP request, which is handier and
more lightweight
than a full-blown
PUT
method, only requires a
PATCH
action:
Chia sẻ với bạn bè của bạn: