Posts Tagged ‘REST API’


July 17, 2016 Leave a comment

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

I found the solution here: 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

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?


from flask import Flask
from flask_restful import Api

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

if production:
    print("# running in production mode")
    HOST = ''
    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
    print("# running in development mode")
    DEBUG = True

# ...

if __name__ == '__main__':, 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: , , ,