RestSharp is a popular .NET library for testing and consuming RESTful APIs in C#. It’s often used for API automation or integration testing within frameworks like NUnit, xUnit, or even combined with SpecFlow for BDD-style testing.

Why Use RestSharp?

FeatureBenefit
Simple APIFluent syntax for making HTTP calls
.NET NativeIntegrates easily with NUnit, MSTest, xUnit
JSON SupportBuilt-in serialization/deserialization
BDD CompatibleCan work with SpecFlow for Gherkin syntax

1. Install RestSharp

dotnet add package RestSharp

For BDD-style tests with SpecFlow:

dotnet add package SpecFlow dotnet add package SpecFlow.NUnit

2. Simple NUnit Test with RestSharp

using NUnit.Framework; using RestSharp; using System.Net; namespace ApiTests { public class LoginTests { private RestClient client; [SetUp] public void Setup() { client = new RestClient("https://reqres.in/api"); } [Test] public void Login_ShouldReturnToken() { var request = new RestRequest("login", Method.Post); request.AddJsonBody(new { email = "eve.holt@reqres.in", password = "cityslicka" }); var response = client.Execute(request); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); dynamic json = SimpleJson.DeserializeObject(response.Content); Assert.IsNotNull(json.token); } } }

3. Using RestSharp with SpecFlow (Optional BDD)

Feature: Login.feature

Feature: Login API Scenario: Successful login Given the API base URL is "https://reqres.in/api" When I send a POST request to "/login" with: | email | eve.holt@reqres.in | | password | cityslicka | Then the response status code should be 200 And the response should contain a token

Step Definitions

using RestSharp; using TechTalk.SpecFlow; using TechTalk.SpecFlow.Assist; using NUnit.Framework; [Binding] public class LoginSteps { private RestClient client; private RestResponse response; [Given(@"the API base URL is ""(.*)""")] public void GivenTheApiBaseUrlIs(string url) { client = new RestClient(url); } [When(@"I send a POST request to ""(.*)"" with:")] public void WhenISendAPOSTRequestToWith(string endpoint, Table table) { var data = table.CreateDynamicInstance(); var request = new RestRequest(endpoint, Method.Post); request.AddJsonBody(new { email = data.email, password = data.password }); response = client.Execute(request); } [Then(@"the response status code should be (.*)")] public void ThenTheResponseStatusCodeShouldBe(int expectedCode) { Assert.AreEqual(expectedCode, (int)response.StatusCode); } [Then(@"the response should contain a token")] public void ThenTheResponseShouldContainAToken() { dynamic json = SimpleJson.DeserializeObject(response.Content); Assert.IsNotNull(json.token); } }