0
0
Flaskframework~5 mins

Mocking external services in Flask

Choose your learning style9 modes available
Introduction

Mocking external services helps you test your Flask app without calling real outside servers. It saves time and avoids errors from network issues.

You want to test your app's response to an external API without using the real API.
You need to simulate slow or failing external services to see how your app handles them.
You want to run tests offline without internet access.
You want to control the data returned by external services for consistent test results.
Syntax
Flask
from unittest.mock import patch
import requests

@patch('requests.get')
def test_function(mock_get):
    mock_get.return_value.status_code = 200
    mock_get.return_value.json.return_value = {'key': 'value'}
    response = requests.get('http://fakeapi.com/data')
    # Your test code here

Use @patch to replace the real external call with a mock during tests.

Set the mock's return values to simulate different responses.

Examples
This mocks a successful API call returning JSON data.
Flask
from unittest.mock import patch
import requests

@patch('requests.get')
def test_success(mock_get):
    mock_get.return_value.status_code = 200
    mock_get.return_value.json.return_value = {'message': 'ok'}
    response = requests.get('http://example.com')
    print(response.json())
This mocks a failed API call returning a 404 status.
Flask
from unittest.mock import patch
import requests

@patch('requests.get')
def test_failure(mock_get):
    mock_get.return_value.status_code = 404
    response = requests.get('http://example.com')
    print(response.status_code)
Sample Program

This Flask app has a route that calls an external API. The test function mocks the external call to return fixed data. When run, it prints the mocked JSON response.

Flask
from flask import Flask, jsonify
import requests
from unittest.mock import patch

app = Flask(__name__)

@app.route('/data')
def get_data():
    response = requests.get('http://external-service.com/api')
    if response.status_code == 200:
        return jsonify(response.json())
    else:
        return jsonify({'error': 'Failed to get data'}), 500

@patch('requests.get')
def test_get_data(mock_get):
    mock_get.return_value.status_code = 200
    mock_get.return_value.json.return_value = {'name': 'Test User', 'age': 30}
    with app.test_client() as client:
        response = client.get('/data')
        print(response.json)

if __name__ == '__main__':
    test_get_data()
OutputSuccess
Important Notes

Always patch the exact location where the external call is used, not where it is defined.

Mocking helps keep tests fast and reliable.

Summary

Mock external services to test your Flask app without real network calls.

Use unittest.mock.patch to replace external calls with fake responses.

This makes your tests faster, more reliable, and easier to control.