NashTech Blog

Validating API Responses in C# with RestSharp and JSON

Table of Contents

APIs are sort of ubiquitous these days. Whether you’re coding away on a side project or buried in production code at the office, you’re likely working with APIs — consuming them, creating them, or both.
Now here’s the catch. APIs are really helpful until they just suddenly break your app. You’re one day receiving that pretty clean JSON with attributes such as id, name, and email, and then next thing you know boom id becomes a string, or email vanishes into thin air. No warning, no notification. And guess what? Your front-end crashes or even worse, silently fails.
it’s the same lesson: if you’re not validating what your API gives you, you’re flying blind. Little changes in the backend can cause really annoying bugs or even open up weird security issues.

Here, we’ll learn how to validate API responses with C#, RestSharp, and JSON Schema. We’ll proceed through the tools, real-world examples, and provide live usage scenarios to make your API data well-structured and trustworthy.

Why Validate API Responses?

Suppose you are working on an app that is dependent on a user profile API. You are expecting it to return user details in a particular format. But suddenly, behind the scenes, a backend update deletes or changes a field without warning. Your frontend then fails, or worse, your business logic begins misbehaving.

That’s the kind of issue response validation aims to prevent. When you validate API responses against a JSON Schema, you can:

Detect missing or extra fields
Catch type mismatches (string vs integer, etc.)
Make sure nested objects are correctly formatted


Enforce required data formats (e.g., date, email)

This process acts as a contract between your frontend/backend or between two services, ensuring both sides are on the same page — literally.

Tools We’ll Use

To begin with, these are the libraries and packages you’ll be needing:

NET Core / .NET 6 or above
RestSharp – for making HTTP API requests
NJsonSchema – a powerful library for JSON schema validation
Newtonsoft.Json (or System.Text.Json) – for JSON parsing (used internally)

Installing Required Packages

Using the .NET CLI, install the following NuGet packages:

dotnet add package RestSharp
dotnet add package NJsonSchema
dotnet add package Newtonsoft.Json

These allow to send API requests and validate the JSON responses against a schema.

Step-by-Step Guide to Validating API Responses

Here is an example where we are making an API request for user information and checking the response .

Step 1: Define Your JSON Schema

Suppose the API is expected to return:

{
  "user_id":101 ,
  "full_name":"Ravi Kumar",
  "contact_email":"ravi.kumar@domain.in"
}

We’ll define the schema like this (save as user-schema.json):

{
  "type": "object",
  "required": ["id", "name", "email"],
  "properties": {
    "id": { "type": "integer" },
    "name": { "type": "string" },
    "email": { "type": "string", "format": "email" }
  }
}

Here every valid response must include all three fields with their respective types.

Step 2: Call the API Using RestSharp

Create a simple RestSharp request to fetch the API data:

using RestSharp;

var client = new RestClient("https://api.example.com");
var request = new RestRequest("/users/1", Method.Get);
var response = await client.ExecuteAsync(request);

This code will send a GET request to the API and capture the response body.

Step 3: Validate the Response with NJsonSchema

Now comes the core part — schema validation:

using NJsonSchema;
using Newtonsoft.Json.Linq;

var schema = await JsonSchema.FromFileAsync("user-schema.json");
var json = JToken.Parse(response.Content);

var errors = schema.Validate(json);

if (errors.Any())
{
    Console.WriteLine("Schema validation failed:");
    foreach (var error in errors)
    {
        Console.WriteLine($"- {error.Path}: {error.Kind}");
    }
}
else
{
    Console.WriteLine("API response is valid ");
}

The Validate method compares the JSON against the schema and returns a list of any issues it finds. You can log, throw exceptions, or fail tests based on these results.

Where This Helps in Real Projects

Let’s talk about how this adds value in different scenarios:

1. Test Automation

Use this in your automated tests to validate that your APIs continue returning valid data after changes. This is especially useful in CI/CD pipelines.

2. Contract Testing

When two groups(frontend and backend) mutually agree on a contract (schema), each can independently ensure that their work is compliant to it.

3. Monitoring and Health Checks

Integrate schema validation in health checks to ensure production APIs are not just “alive” but returning the right structure.

4. Third-party Integrations

If you consume data from external APIs, validate their responses so your system doesn’t break when they make unexpected changes.

Tips for Writing Robust Schemas

Use required for all must-have fields
Specify type for each property (avoid loose validation)
Use format for fields like emails, dates, and URIs
Add minLength, maxLength, pattern, etc., where neededKeep schemas version-controlled alongside your code

Conclusion

It’s not difficult to validate API responses with JSON Schema in C# — and it’s one of those little things that provide big payoff. With minimal lines of code, you can avoid downstream errors, maintain data integrity, and establish confidence in your API layer.Whether you’re a solo coder, part of a high-speed startup team, or a large enterprise team — automated response validation should be the norm in your development culture.Use RestSharp to talk, NJsonSchema to validate, and sleep well knowing your APIs are acting as they should.

For more Tech related blogs refer to Nashtech blogs.

Reference

1. “RESTful Web APIs” by Leonard Richardson & Mike Amundsen
2. “Designing Web APIs” by Brenda Jin, Saurabh Sahni, Amir Shevat
3. “C# 12 and .NET 8 – Modern Cross-Platform Development” by Mark J. Price

Picture of souravmishra538826d744

souravmishra538826d744

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top