HTTP GET is a request method used to retrieve a representation of a resource. For a file-listing API, a client can send GET to /files and receive a JSON array describing the available files. section 4.3.1 section 4.7
Start with a simple route that returns known data. The asynchronous read_files function uses a router decorator to associate the GET method with the files route; its response is hardcoded until real file information is available. section 4.3.1
Listing 4.3 Our first API route
@router.get("/files/") #1
async def read_files(): #2
return [{"file": "File_1"}, {"file": "File_2"}] #2
This route returns two file entries as a JSON array. section 4.3.1
Test the endpoint with FastAPI’s TestClient and pytest. Send client.get("/files"), then check both the 200 status and the expected JSON. To confirm the test is actually checking your logic, temporarily change an expected value, endpoint, or request type and verify that the test fails. section 4.3.1
Listing 4.4 Testing our first endpoint
from fastapi import FastAPI #1
from fastapi.testclient import TestClient #1
from app.main import app #1
client = TestClient(app) #2
def test_read_files(): #3
response = client.get("/files") #4
assert response.status_code == 200 #5
assert response.json() == #5
➥[{"file": "File_1"}, {"file": "File_2"}] #5
The test checks the response status and the two hardcoded file entries. section 4.3.1
For a separate QA check, create a GET request in a Postman collection, point it to http://localhost:8000/files, and select Send. After inspecting the JSON response, add tests for the status and response data. These checks can also be used in a larger CI/CD or QA process. section 4.7
Be careful with tests that depend on array position: File_1 might not always be first. Search the array instead to check that the expected file is present without relying on its position. section 4.7
Listing 4.16 Cleaning up our test
pm.test("There should be one instance of File_1 using some", function () {
const expectedValue = 'File_1';
const result = jsonData.some(function (item) {
return item.file === expectedValue;
});
pm.expect(result).to.be.true;
})
This Postman test uses some to check for File_1 anywhere in the response array. section 4.7
















