Archive

Posts Tagged ‘REST API’

Flask RESTful POST JSON

July 17, 2016 Leave a comment

Problem
Using Flask-RESTful, I needed an API endpoint that accepts JSON data.

Solution
I found the solution here: http://stackoverflow.com/questions/22273671/flask-restful-post-json-fails. You can copy / paste that code. Note that the JSON data is POSTed to your API endpoint, thus you need to implement the post() method.

However, how to test it?

1) using cURL:

$ curl -i -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d "{\"Hello\":\"Karl\"}" http://domain/your_api_endpoint

Damn, that’s compicated, right? Is there an easier way?

2) using httpie:
You can install httpie with your favorite package manager. Then:

$ http POST http://domain/your_api_endpoint Hello=Karl

pretty JSON output with Flask-RESTful

March 15, 2016 Leave a comment

Problem
Flask-RESTful is an awesome way to write REST APIs. In debug mode, its output is nicely indented, easy to read. However, in production mode the JSON is compressed and hard to read.

If debug is False, how to have a nicely formatted output?

Solution

from flask import Flask
from flask_restful import Api

app = Flask(__name__)
api = Api(app)

if production:
    print("# running in production mode")
    HOST = '0.0.0.0'
    DEBUG = False
    # START: temporary help for the UI developers, remove later
    settings = app.config.get('RESTFUL_JSON', {})
    settings.setdefault('indent', 2)
    settings.setdefault('sort_keys', True)
    app.config['RESTFUL_JSON'] = settings
    # END
else:
    print("# running in development mode")
    HOST='127.0.0.1'
    DEBUG = True

# ...

if __name__ == '__main__':
    app.run(debug=DEBUG, host=HOST, port=1234)

Note that here I use the development server shipped with Flask, which is not suitable for real production. So this solution is between development and production.

Categories: flask, python Tags: , , ,