Created
February 13, 2023 15:43
-
-
Save deangrant/4e189833bdb618dbd8b499aef0908cbc to your computer and use it in GitHub Desktop.
A code block that parses a JSON object from an HTTP request validates it contents, and raises an error if it is invalid.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import ( | |
request | |
) | |
required_fields: [ | |
# Add list of required field names. | |
] | |
# Parse request data as JSON. | |
data = request.get_json() | |
# If request data is empty, raise a KeyError. | |
if not data: | |
raise KeyError( | |
"The request body provided is empty." | |
) | |
# Check that all required fields are present in request data. | |
for field in required_fields: | |
if field not in data: | |
# Raise a KeyError if any required field is missing. | |
raise KeyError( | |
f"The required field name {field} is not specified." | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment