0
0
Rest APIprogramming~5 mins

Integration testing in Rest API

Choose your learning style9 modes available
Introduction

Integration testing checks if different parts of a program work well together. It helps find problems when pieces connect.

When you want to test if your API endpoints work correctly with the database.
When you add a new feature that uses multiple services and want to check they communicate properly.
When you fix a bug that might affect how different parts of your app interact.
Before releasing your app to make sure all parts work as expected together.
Syntax
Rest API
def test_api_integration():
    response = client.get('/api/resource')
    assert response.status_code == 200
    assert 'expected_key' in response.json()

This example shows a simple integration test for a REST API endpoint.

Use a test client to send requests and check responses.

Examples
Test if getting user with ID 1 returns correct data.
Rest API
def test_get_user():
    response = client.get('/users/1')
    assert response.status_code == 200
    assert response.json()['id'] == 1
Test creating a new post via POST request and check response.
Rest API
def test_create_post():
    data = {'title': 'Hello', 'content': 'World'}
    response = client.post('/posts', json=data)
    assert response.status_code == 201
    assert response.json()['title'] == 'Hello'
Sample Program

This program creates a simple API with two endpoints: one to add posts and one to get all posts. The test sends a post, then checks if it was saved and can be retrieved.

Rest API
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

posts = []

@app.post('/posts')
def create_post(post: dict):
    posts.append(post)
    return post

@app.get('/posts')
def get_posts():
    return posts

client = TestClient(app)

def test_create_and_get_posts():
    new_post = {'title': 'Test', 'content': 'Integration'}
    response = client.post('/posts', json=new_post)
    assert response.status_code == 201
    assert response.json() == new_post

    response = client.get('/posts')
    assert response.status_code == 200
    assert new_post in response.json()

if __name__ == '__main__':
    test_create_and_get_posts()
    print('Integration test passed')
OutputSuccess
Important Notes

Integration tests are slower than unit tests because they test multiple parts together.

Keep integration tests focused on how parts work together, not on internal details.

Use test databases or mock services to avoid changing real data.

Summary

Integration testing checks if different parts of your app work together correctly.

It is useful for testing API endpoints, databases, and service communication.

Write tests that send requests and check responses to catch connection problems early.