Skip to content

Instantly share code, notes, and snippets.

@deangrant
Created February 13, 2023 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deangrant/4e189833bdb618dbd8b499aef0908cbc to your computer and use it in GitHub Desktop.
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.
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