Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Flask JSON API

If instead of a string we return a dictionary, Flask will assume it is an API endpoint and will return a serialized version of the data structure.

from flask import Flask
app = Flask(__name__)

@app.route("/")
def main():
    return '''
Main <a href="/api/info">info</a>
'''

@app.route("/api/info")
def api_info():
    info = {
       "ip" : "127.0.0.1",
       "hostname" : "everest",
       "description" : "Main server",
       "load" : [ 3.21, 7, 14 ]
    }
    return info
$ curl -I http://localhost:5000/api/info
HTTP/1.0 200 OK
Content-Type: application/json
import return_json
import pytest

@pytest.fixture()
def web():
    return return_json.app.test_client()

def test_main_page(web):
    rv = web.get('/')
    assert rv.status == '200 OK'
    assert b'Main <a href="/api/info">info</a>' in rv.data

def test_info(web):
    rv = web.get('/api/info')
    assert rv.status == '200 OK'
    #print(rv.data) # the raw json data
    assert rv.headers['Content-Type'] == 'application/json'
    resp = rv.json
    assert resp == {
       "ip" : "127.0.0.1",
       "hostname" : "everest",
       "description" : "Main server",
       "load" : [ 3.21, 7, 14 ]
    }

Client in Python

import requests

res = requests.get("http://localhost:5000/api/info")
print(res.status_code)
print(res.text)
print(type(res.text))
data = res.json()
print(type(data))
print(data)
print(data["hostname"])