0
0
Djangoframework~30 mins

Testing API endpoints in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Testing API endpoints
📖 Scenario: You are building a simple Django API for a bookstore. You want to make sure your API endpoints work correctly by writing tests.
🎯 Goal: Write tests for the API endpoints to check that the responses return the expected status codes and data.
📋 What You'll Learn
Create a test client to send requests to the API
Write a test to check the GET request to the book list endpoint
Write a test to check the POST request to add a new book
Verify the response status codes and returned data in tests
💡 Why This Matters
🌍 Real World
Testing API endpoints ensures your web services work correctly and reliably before users interact with them.
💼 Career
API testing is a key skill for backend developers and QA engineers to maintain quality and prevent bugs in web applications.
Progress0 / 4 steps
1
Set up test data
Create a list called books with two dictionaries representing books. Each dictionary should have 'title' and 'author' keys with these exact values: {'title': 'Django for Beginners', 'author': 'William S. Vincent'} and {'title': 'Two Scoops of Django', 'author': 'Daniel Roy Greenfeld'}.
Django
Need a hint?

Use a list with two dictionaries exactly as shown.

2
Configure the test client
Import APIClient from rest_framework.test and create a variable called client that is an instance of APIClient().
Django
Need a hint?

Import APIClient and create client = APIClient().

3
Write a test for GET /books/
Write a function called test_get_books() that uses client.get to request the '/books/' endpoint. Inside the function, assign the response to a variable called response. Then check that response.status_code equals 200 and that response.data equals the books list.
Django
Need a hint?

Define test_get_books(), call client.get('/books/'), and assert status code and data.

4
Write a test for POST /books/
Write a function called test_post_book() that uses client.post to send a new book dictionary {'title': 'Effective Django', 'author': 'Brett Slatkin'} to the '/books/' endpoint with format='json'. Assign the response to response. Then check that response.status_code equals 201 and that response.data contains the new book dictionary.
Django
Need a hint?

Define test_post_book(), post the new book with format='json', and assert status code and data.