Skip to content

Instantly share code, notes, and snippets.

@lost-theory
Created June 27, 2012 16:35
Show Gist options
  • Save lost-theory/3005268 to your computer and use it in GitHub Desktop.
Save lost-theory/3005268 to your computer and use it in GitHub Desktop.
consume JSON REST API blueprint inside flask app
from flask import Flask, jsonify, Blueprint, current_app
import json
## REST api ###################################################################
api = Blueprint('api', __name__)
@api.route("/users")
def users():
return jsonify(users=[
{"username": "alice", "user_id": 1},
{"username": "bob", "user_id": 2},
])
## app ########################################################################
app = Flask(__name__)
app.config["DEBUG"] = True
app.register_blueprint(api, url_prefix="/v1")
def get_json_response(view_name, *args, **kwargs):
'''Calls internal view method, parses json, and returns python dict.'''
view = current_app.view_functions[view_name]
res = view(*args, **kwargs)
#XXX: to avoid the json decode internally for every call,
#you could make your own jsonify function that used a subclass
#of Response which has an attribute with the underlying
#(non-JSON encoded) data
js = json.loads(res.data)
return js
@app.route("/")
def index():
js = get_json_response('api.users')
usernames = [u['username'] for u in js['users']]
return "<h1>Hello</h1><p>Users are: %r</p>" % usernames #XXX: render a template here
###############################################################################
if __name__ == "__main__":
app.run(use_debugger=True, use_reloader=True)
@dougngo
Copy link

dougngo commented Dec 9, 2015

what if api.user has parameters? such as /users?level=administrators ... How would I retrieve the query param "level" .

Lastly, does this only for get requests? what about posts/put, etc...

@kampta
Copy link

kampta commented Jun 27, 2016

Just tried parsing arguments in the users function

@api.route("/users")
def users():
    level = request.args.get('level', None)
    return ...

But doesn't work :(

@deeshank
Copy link

How do u make a post request to internal api?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment