Skip to content

Instantly share code, notes, and snippets.

@lrei
Created April 17, 2012 19:16
Show Gist options
  • Save lrei/2408383 to your computer and use it in GitHub Desktop.
Save lrei/2408383 to your computer and use it in GitHub Desktop.
Flask Rest Api Example Route
@app.route('/users/<username>', methods = ['GET', 'POST', 'PATCH', 'DELETE'])
@requires_auth
def api_user(username):
current_user = User.get(request.authorization.username)
app.logger.debug("req.auth.username = %s", request.authorization.username)
# Only "SELF" can access/modify user info
if current_user.username != username:
return unauthorized()
app.logger.debug("Inside /users/%s" % username)
# GET
if request.method == 'GET':
app.logger.debug("METHOD IS GET")
rendered = current_user.json()
# @TODO IMPLEMENT THE MIMETYPE PROPERLY INSIDE USER
#mimetype = 'application/vnd.newsrdr.com.user+json;version=1.0'
mimetype = 'application/json'
return Response(rendered, 200, mimetype=mimetype)
# PATCH/POST
if request.method == 'PATCH' or request.method == 'POST':
app.logger.debug("METHOD IS PATCH OR POST")
app.logger.debug("r.data = %s" % request.data)
if current_user.update(request.json) is False:
return bad_request(info=request.json)
mimetype = 'application/json'
return Response(status=200, mimetype=mimetype)
if request.method == 'DELETE':
mimetype='application/json'
return Response(status=501, mimetype=mimetype)
# METHOD NOT ALLOWED
return Response(status=405)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment