Validating API Responses

The QA Chronicles
2 min readAug 20, 2023

When building applications that consume APIs, it’s crucial to validate the responses you receive to prevent bugs and errors down the line. There are a few key ways to validate API responses:

1. Check Status Codes

The first validation to perform is checking the status code of the response. Common status codes like 200, 400, 404, 500 etc give you information on whether the request succeeded or failed. You can check the status code in most programming languages like:

if (response.statusCode === 200) {
// API call succeeded
} else {
// Handle error
}

Be sure to account for all status codes the API could return, not just 200 and 404.

2. Validate the Response Structure

Next, you’ll want to validate the structure of the response body matches what you expect from the API documentation. This is where defining JSON Schema comes in handy.

JSON Schema allows you to model the structure of the expected response. You can define the required fields, data types, nested objects and more. For example:

{
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"scores": {
"type": "array",
"items": {
"type": "integer"
}
}
}
}

This schema could then be used to validate the shape of the response body. Any deviations from the schema would be flagged as errors.

3. Check for Expected Values

Beyond just the structure, you may want to check for specific values in the response. For example, validating that:

  • A status field equals “success”
  • An error message matches a known string
  • A set of values fall in an expected range

You can perform these checks by writing assertions in your test code against the response body.

Conclusion

Validating API responses by checking status codes, matching against a schema, and asserting expected values will go a long way in preventing tricky bugs in your application. Building these validations will make your app more resilient to changes in the API down the line.

Some libraries that can help with API response validation include JSON Schema, Jest, and SuperTest. Look into the validation options available in your language and testing framework of choice. Add response validation to your API calls today!

--

--