0
0
Flaskframework~30 mins

Mocking external services in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Mocking External Services in Flask
📖 Scenario: You are building a Flask web app that fetches weather data from an external API. To test your app without calling the real API every time, you will mock the external service.
🎯 Goal: Create a Flask app that calls a mocked weather API service and returns the mocked data as JSON.
📋 What You'll Learn
Create a Flask app with a route /weather
Mock the external weather API call to return fixed data
Use the unittest.mock library to patch the external call
Return the mocked weather data as JSON from the route
💡 Why This Matters
🌍 Real World
Mocking external services is useful when you want to test your Flask app without relying on real APIs that may be slow, unreliable, or cost money.
💼 Career
Many jobs require writing tests for web apps that depend on external services. Knowing how to mock these services helps ensure your app works correctly and tests run fast.
Progress0 / 4 steps
1
Set up Flask app and route
Create a Flask app instance called app and define a route /weather with a function get_weather that returns an empty dictionary as JSON.
Flask
Need a hint?

Use Flask(__name__) to create the app and @app.route('/weather') to define the route.

2
Add external API call function
Create a function called fetch_weather_data that simulates calling an external API by returning a dictionary {'temp': 20, 'condition': 'Sunny'}. Update get_weather to call fetch_weather_data and return its result as JSON.
Flask
Need a hint?

Define fetch_weather_data to return the fixed dictionary. Call it inside get_weather.

3
Mock the external API call in a test
Write a test function called test_get_weather that uses unittest.mock.patch to replace fetch_weather_data with a mock returning {'temp': 10, 'condition': 'Cloudy'}. Inside the test, call get_weather and check that the returned JSON matches the mocked data.
Flask
Need a hint?

Use @patch decorator to mock fetch_weather_data. Call get_weather() and assert the JSON matches the mock.

4
Run Flask app with debug mode
Add the standard Flask app runner code to run the app with debug=True when the script is executed directly.
Flask
Need a hint?

Add the if __name__ == '__main__': block and call app.run(debug=True) inside it.