Complete worked example
python
from flask import Flask, request
from werkzeug.exceptions import BadRequest, UnsupportedMediaType
app = Flask(__name__)
app.config.update(TESTING=True, MAX_CONTENT_LENGTH=128)
@app.post('/roles')
def create():
try:
body = request.get_json()
except (BadRequest, UnsupportedMediaType) as error:
return {'error': 'json required'}, error.code
if not isinstance(body, dict) or type(body.get('title')) is not str:
return {'error': 'title required'}, 400
title = body['title'].strip()
if not title or len(title) > 20:
return {'error': 'title invalid'}, 400
return {'title': title}, 201
def submit(raw, content_type='application/json'):
response = app.test_client().post('/roles', data=raw, content_type=content_type)
return {'status': response.status_code, 'body': response.json}- Reasoning
- This endpoint accepts a short string title inside an object, trims surrounding whitespace and returns the cleaned title with status 201. get_json keeps its standard media-type and parse behavior.