Sobes.tech
Junior — Middle

How can you verify the correctness of working with an external API or service in your application?

sobes.tech AI

Answer from AI

To verify the correctness of working with an external API in Python, several approaches are usually used:

  • Mocking requests using libraries such as unittest.mock or responses. This allows simulating API responses without real network calls, speeding up tests and making them more stable.

  • Integration tests that make real requests to a test API environment to verify correct interaction.

  • Response validation: checking the structure and content of responses (for example, using jsonschema) to ensure data meets expectations.

Example of mocking a request using requests and responses:

import requests
import responses

@responses.activate
def test_api_call():
    responses.add(responses.GET, 'https://api.example.com/data',
                  json={'key': 'value'}, status=200)

    resp = requests.get('https://api.example.com/data')
    assert resp.status_code == 200
    assert resp.json() == {'key': 'value'}