RestSharp API Testing in C#: Complete Guide
Learn RestSharp API testing in C# with step-by-step examples in 2026. Setup, GET/POST/PUT/DELETE, authentication, JSON serialization, and CI/CD integration.

In this article
- What is RestSharp?
- Install RestSharp
- Your First GET Request
- Deserialize JSON Response
- POST with JSON Body
- PUT and DELETE
- Authentication
- Query and Path Parameters
- Verify Status Code (Assertions)
- Verify Response Body with JSON Path
- RestSharp vs HttpClient
- CI/CD Integration
- Common Patterns
- Advanced Patterns
- Continue your learning
- Frequently asked questions
Last updated: June 27, 2026 · 8 min read
RestSharp is the most popular HTTP client library for .NET API testing. This guide walks you from setup to advanced patterns in 15 minutes. Pair it with our API Testing Tutorial, Postman API Testing, and SpecFlow C# Automation guide.
What is RestSharp?
RestSharp is a simple REST and HTTP API client for .NET. It wraps HttpClient with a fluent API that handles JSON serialization, authentication, and error handling out of the box. The library is maintained on GitHub and documented on restsharp.dev.
Install RestSharp
dotnet add package RestSharp
dotnet add package Newtonsoft.JsonYour First GET Request
using RestSharp;
var client = new RestClient("https://api.example.com");
var request = new RestRequest("/users/1", Method.Get);
var response = await client.ExecuteAsync(request);
Console.WriteLine(response.StatusCode); // 200
Console.WriteLine(response.Content); // {"id":1,"name":"Alice"}Deserialize JSON Response
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
var response = await client.ExecuteAsync<User>(request);
var user = response.Data;
Console.WriteLine(user.Name); // "Alice"POST with JSON Body
var request = new RestRequest("/users", Method.Post)
.AddJsonBody(new
{
name = "Alice",
email = "alice@example.com"
});
var response = await client.ExecuteAsync(request);
Assert.AreEqual(201, (int)response.StatusCode);PUT and DELETE
// PUT
var updateRequest = new RestRequest("/users/1", Method.Put)
.AddJsonBody(new { name = "Alice Updated" });
await client.ExecuteAsync(updateRequest);
// DELETE
var deleteRequest = new RestRequest("/users/1", Method.Delete);
await client.ExecuteAsync(deleteRequest);Authentication
Bearer Token
var client = new RestClient("https://api.example.com");
client.AddDefaultHeader("Authorization", $"Bearer {token}");
var request = new RestRequest("/admin/users", Method.Get);
var response = await client.ExecuteAsync(request);Basic Auth
client.Authenticator = new HttpBasicAuthenticator("admin", "Sup3rSecret!");Query and Path Parameters
Query parameters
var request = new RestRequest("/users", Method.Get)
.AddQueryParameter("page", "1")
.AddQueryParameter("limit", "10");Path parameters
var request = new RestRequest("/users/{id}", Method.Get)
.AddUrlSegment("id", "1");Verify Status Code (Assertions)
Use NUnit, xUnit, or MSTest:
using NUnit.Framework;
Assert.That((int)response.StatusCode, Is.EqualTo(200));
Assert.That(response.IsSuccessful, Is.True);For more on API testing strategy, see our API Testing Tutorial.
Verify Response Body with JSON Path
Install JsonPath:
dotnet add package JsonPath.Netusing JsonPath;
var json = JObject.Parse(response.Content);
var name = json.SelectToken("$.name");
Assert.That(name?.ToString(), Is.EqualTo("Alice"));RestSharp vs HttpClient
| Dimension | RestSharp | HttpClient |
|---|---|---|
| Setup | Simple | Verbose |
| JSON serialization | Built-in | Manual |
| Authentication helpers | Yes | Manual |
| Async support | Yes | Yes |
| Performance | Slightly slower | Faster |
| Best for | API testing | Production HTTP clients |
For production code, use HttpClient (faster, more control). For API testing, RestSharp wins on developer experience.
CI/CD Integration
- uses: actions/setup-dotnet@v4
with: { dotnet-version: '8.0.x' }
- run: dotnet test --logger "trx;LogFileName=results.trx"
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with: { name: test-results, path: TestResults/ }For more CI patterns, see our GitHub Actions Selenium CI guide.
Common Patterns
Reusable client setup
public class ApiClient
{
private readonly RestClient _client;
public ApiClient(string baseUrl) { _client = new RestClient(baseUrl); }
public async Task<RestResponse<T>> GetAsync<T>(string path)
=> await _client.ExecuteAsync<T>(new RestRequest(path, Method.Get));
public async Task<RestResponse<T>> PostAsync<T>(string path, object body)
{
var request = new RestRequest(path, Method.Post).AddJsonBody(body);
return await _client.ExecuteAsync<T>(request);
}
public async Task<RestResponse> DeleteAsync(string path)
=> await _client.ExecuteAsync(new RestRequest(path, Method.Delete));
}Request interceptor
client.AddRequestInterceptor(req => {
Console.WriteLine($"→ {req.Method} {req.Resource}");
return req;
});File upload
var request = new RestRequest("/upload", Method.Post)
.AddFile("file", "/path/to/file.png", "image/png");
var response = await client.ExecuteAsync(request);Advanced Patterns
Async/Await best practice
// ❌ Bad — blocks the thread
var response = client.Execute(request);
// ✅ Good — async, scalable
var response = await client.ExecuteAsync(request);Handling rate limits
public async Task<RestResponse> ExecuteWithRetry(RestRequest request, int maxRetries = 3)
{
for (int i = 0; i < maxRetries; i++)
{
var response = await client.ExecuteAsync(request);
if (response.StatusCode != HttpStatusCode.TooManyRequests)
return response;
var retryAfter = response.Headers
.FirstOrDefault(h => h.Name == "Retry-After")?.Value ?? "1";
await Task.Delay(int.Parse(retryAfter) * 1000);
}
throw new Exception("Rate limit exceeded");
}Mocking external APIs with WireMock.NET
dotnet add package WireMock.Netvar server = WireMockServer.Start(8080);
server.Given(Request.Create().WithPath("/api/external").UsingGet())
.RespondWith(Response.Create().WithStatusCode(200)
.WithBody("{ \"id\": 1, \"name\": \"Mock\" }"));
var client = new RestClient("http://localhost:8080");Schema validation
var schemaJson = File.ReadAllText("schemas/user.json");
var schema = JSchema.Parse(schemaJson);
var response = await client.ExecuteAsync(request);
var body = JObject.Parse(response.Content);
var isValid = body.IsValid(schema, out var errors);
Assert.That(isValid, Is.True);Continue your learning
Frequently asked questions
Is RestSharp still relevant in 2026?
Yes — RestSharp v110+ is actively maintained. It's the most popular HTTP client for .NET API testing.
RestSharp vs HttpClient — which should I use?
Use RestSharp for API testing (faster development, less boilerplate). Use HttpClient for production code (better performance, more control).
Can RestSharp deserialize JSON automatically?
Yes — pass a type to ExecuteAsync<T>() and RestSharp handles JSON deserialization via its built-in JsonSerializer.
Does RestSharp support OAuth 2.0?
Yes — via the OAuth2Authenticator or by adding a Bearer token header manually with AddDefaultHeader.
Can I use RestSharp with SpecFlow?
Yes — RestSharp integrates naturally with SpecFlow step definitions. See our SpecFlow C# Automation guide for end-to-end examples.
Practice these questions
Rehearse REST, Postman, REST Assured and contract-testing questions with worked examples.
Was this article helpful?
Keep building your QA edge
Pillar guides- Postman TutorialPostman API testing tutorialPostman from zero to CI — collections, scripts, Newman.
- AI Mock Interviewrehearse out loud with our coachLive AI-powered mock interviews with rubric feedback.
- ATS Resume ReviewSoftwareTestPilot's ATS resume checkerFree AI ATS scoring with rewrite suggestions.
Continue reading
Join the QA Community
Connect with fellow testers, share job leads, and get career advice.
Stop Reinventing the Wheel. Upgrade Your QA Arsenal.
Take your testing skills from beginner to Lead Engineer. Supercharge your daily workflow with our premium digital resources.
- ⚡ Ready-to-use testing strategy templates
- 🔥 Advanced API & UI automation guides
- ⏱️ Save 10+ hours a week on test planning


