Flask Testing Testing a JSON API implemented in Flask

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9

Example

This example assumes you know how to test a Flask app using pytest

Below is an API that takes a JSON input with integer values a and b e.g. {"a": 1, "b": 2}, adds them up and returns sum a + b in a JSON response e.g. {"sum": 3}.

# hello_add.py
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/add', methods=['POST'])
def add():
    data = request.get_json()
    return jsonify({'sum': data['a'] + data['b']})

Testing this API with pytest

We can test it with pytest

# test_hello_add.py
from hello_add import app
from flask import json

def test_add():        
    response = app.test_client().post(
        '/add',
        data=json.dumps({'a': 1, 'b': 2}),
        content_type='application/json',
    )

    data = json.loads(response.get_data(as_text=True))

    assert response.status_code == 200
    assert data['sum'] == 3

Now run the test with py.test command.



Got any Flask Question?