Customizing
APIRoute and Request
301
async def body(self):
body = await super().body()
login_dict = ast.literal_eval(body.decode('utf-8'))
fernet = Fernet(bytes(login_dict['key'],
encoding='utf-8'))
data = fernet.decrypt(
bytes(login_dict['enc_login'], encoding='utf-8'))
self.state.dec_data = json.loads(
data.decode('utf-8'))
return body
Important note
The
cryptography
module requires the installation of the
itsdangerous
extension for
the encryption/decryption procedure used in this project.
DecryptRequest
will decrypt the message and return the list of
login records as a request
state
object. The following service provides the encrypted message body and key and returns the decrypted
list
of login records from
DecryptRequest
as a response:
@router.post("/login/decrypt/details")
async def send_decrypt_login(
enc_data: EncLoginReq
,
req:Request, user: str = Depends(get_current_user)):
return {"data" : req.state.dec_data}
Note that
send_decrypt_login()
has an
EncLoginReq
request
model that contains the
encrypted message body and the encryption key from the client.
Customizing the routes and their
Request
objects can help optimize and streamline microservice
transactions, especially those API endpoints that require heavy loads
on message body conversions,
transformations, and computations.
Now, our next discussion will focus on applying different
Response
types for the API services.
Utilizing
Other Advanced Features
302
Choosing the appropriate responses
The FastAPI framework offers other options for rendering API endpoint responses other than the
most
common
JsonResponse
option. Here is a list of some of the response types supported by
FastAPI and their corresponding samples from our application:
• The API endpoints can utilize the
PlainTextResponse
type if their response is text-based
only. The following
intro_list_restaurants()
service returns
a text-based message
to the client:
Chia sẻ với bạn bè của bạn: