Skip to content

Instantly share code, notes, and snippets.

@tecoholic
Last active August 16, 2019 06:04
Show Gist options
  • Save tecoholic/a0c29807f079d6acba8a502229b8f50a to your computer and use it in GitHub Desktop.
Save tecoholic/a0c29807f079d6acba8a502229b8f50a to your computer and use it in GitHub Desktop.
Example code for the post "Parsing & Validating JSON in Flask Requests"
from flask import Flask, request, jsonify
from functools import wraps
app = Flask(__name__)
users = []
def required_params(required):
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
_json = request.get_json()
missing = [r for r in required.keys()
if r not in _json]
if missing:
response = {
"status": "error",
"message": "Request JSON is missing some required params",
"missing": missing
}
return jsonify(response), 400
wrong_types = [r for r in required.keys()
if not isinstance(_json[r], required[r])]
if wrong_types:
response = {
"status": "error",
"message": "Data types in the request JSON doesn't match the required format",
"param_types": {k: str(v) for k, v in required.items()}
}
return jsonify(response), 400
return fn(*args, **kwargs)
return wrapper
return decorator
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route("/user/", methods=["POST"])
@required_params({"first_name": str, "last_name": str, "age": int, "married": bool})
def add_user():
# here a simple list is used in place of a DB
users.append(request.get_json())
return "OK", 201
if __name__ == '__main__':
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment