ZetCode

C# RestSharp

last modified October 18, 2026

In this article we show how to create HTTP requests with the RestSharp library in C#.

The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.

RestSharp is a simple REST and HTTP API client for .NET. It is a wrapper around HttpClient that adds a fluent request builder, JSON and XML serialization, authenticators, and convenient handling of parameters, headers, and files. For simple cases, HttpClient alone is enough; RestSharp helps when an application talks to many endpoints of a REST API. See the C# HttpClient tutorial for the built-in alternative.

$ dotnet add package RestSharp

We add the package to the project. The examples use RestSharp 114.

The test server

The examples talk to a small REST API that runs on localhost:5060, so that we can try every HTTP method and error without depending on a public site. It is a single-file ASP.NET Core minimal API (.NET 10); we start it with dotnet run todo-api.cs in a separate terminal.

todo-api.cs
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false

using System.Text.Json;

var app = WebApplication.Create(args);

var todos = new List<Todo> { new(1, "buy milk", false), new(2, "write article", true) };

app.MapGet("/todos", (int? limit) => limit is null ? todos : todos.Take(limit.Value));
app.MapGet("/todos/{id:int}", (int id) => todos.FirstOrDefault(t => t.Id == id) is { } t ? Results.Ok(t) : Results.NotFound());
app.MapPost("/todos", (NewTodo n) =>
{
    var t = new Todo(todos.Max(x => x.Id) + 1, n.Title, false);
    todos.Add(t);
    return Results.Created($"/todos/{t.Id}", t);
});
app.MapPut("/todos/{id:int}", (int id, NewTodo n) => Results.Ok(new Todo(id, n.Title, true)));
app.MapDelete("/todos/{id:int}", (int id) => Results.NoContent());
app.MapGet("/ua", (HttpRequest r) => r.Headers.UserAgent.ToString());
app.MapGet("/secure", (HttpRequest r) => r.Headers.Authorization == "Bearer secret" ? Results.Ok("welcome") : Results.Unauthorized());
app.MapGet("/slow", async () => { await Task.Delay(3000); return "late"; });
app.MapGet("/flaky", (HttpContext c) => c.Request.Query["n"] == "1" ? Results.StatusCode(503) : Results.Ok("ok"));
app.MapPost("/form", (HttpRequest r) => r.Form.ToDictionary(k => k.Key, v => v.Value.ToString()));
app.MapPost("/upload", async (IFormFile file) =>
{
    using var sr = new StreamReader(file.OpenReadStream());
    return new { file.FileName, file.Length, Content = await sr.ReadToEndAsync() };
}).DisableAntiforgery();
app.MapGet("/search", (string q, int page) => new { q, page });
app.MapMethods("/head", ["GET", "HEAD"], () => Results.Ok("body"));

app.Run("http://localhost:5060");

record Todo(int Id, string Title, bool Completed);
record NewTodo(string Title);

It has a list of todo items and endpoints to read, add, change and delete them, and a few helper endpoints that return the User-Agent header, require a bearer token, answer slowly, or fail on the first attempt. The #:property PublishAot=false line is needed because file-based apps default to Native AOT, which does not allow the reflection-based JSON that minimal APIs use here.

C# RestSharp GET request

The GET method requests a representation of the specified resource. The GetAsync method executes the request asynchronously using the GET HTTP method.

Program.cs
using RestSharp;
using System.Text.Json.Nodes;

using var client = new RestClient("http://localhost:5060");
var req = new RestRequest("todos/2");
RestResponse resp = await client.GetAsync(req);

Console.WriteLine($"{(int)resp.StatusCode} {resp.StatusCode}, successful: {resp.IsSuccessful}");
Console.WriteLine(resp.ContentType);

var data = JsonNode.Parse(resp.Content!)!;

Console.WriteLine(data["id"]);
Console.WriteLine(data["title"]);
Console.WriteLine(data["completed"]);
Console.WriteLine(data);

We generate an asynchronous GET request to the API.

using var client = new RestClient("http://localhost:5060");
var req = new RestRequest("todos/2");
RestResponse resp = await client.GetAsync(req);

We build a RestClient with the base address and execute an asynchronous request with the GetAsync method. The RestRequest holds the resource path relative to the base address. The result is a RestResponse with the status code, headers, and the body in the Content property.

var data = JsonNode.Parse(resp.Content!)!;

We parse the JSON response into a JsonNode object.

Console.WriteLine(data["id"]);
Console.WriteLine(data["title"]);
Console.WriteLine(data["completed"]);

We print the fields of the data object.

$ dotnet run
200 OK, successful: True
application/json
2
write article
true
{
  "id": 2,
  "title": "write article",
  "completed": true
}

C# RestSharp deserialize JSON

In the next example, we let RestSharp deserialize the returned data into custom objects. The generic overloads of GetAsync do the request and the deserialization in one call.

Program.cs
using RestSharp;

using var client = new RestClient("http://localhost:5060");

// the typed overload deserializes the JSON body with System.Text.Json
Todo? todo = await client.GetAsync<Todo>("todos/1");
Console.WriteLine(todo);

List<Todo>? todos = await client.GetAsync<List<Todo>>("todos");
todos!.ForEach(Console.WriteLine);

// a request object gives more control
var req = new RestRequest("todos/{id}").AddUrlSegment("id", 2);
Todo? second = await client.GetAsync<Todo>(req);
Console.WriteLine(second?.Title);

record Todo(int Id, string Title, bool Completed);

The returned data is deserialized into Todo objects.

Todo? todo = await client.GetAsync<Todo>("todos/1");

The JSON is deserialized with System.Text.Json. RestSharp's default options are the web defaults, so property names are matched case-insensitively and id fills Id. The method returns null when the server answers with a 404 status.

var req = new RestRequest("todos/{id}").AddUrlSegment("id", 2);

A placeholder in curly braces is replaced by AddUrlSegment, which also encodes the value. The fluent Add... methods return the request, so they can be chained.

$ dotnet run
Todo { Id = 1, Title = buy milk, Completed = False }
Todo { Id = 1, Title = buy milk, Completed = False }
Todo { Id = 2, Title = write article, Completed = True }
write article

C# RestSharp query parameters

Query parameters are added to the request with AddQueryParameter. RestSharp encodes the names and the values.

Program.cs
using RestSharp;

using var client = new RestClient("http://localhost:5060");

var req = new RestRequest("search")
    .AddQueryParameter("q", "rest sharp & friends")
    .AddQueryParameter("page", 2);

var resp = await client.ExecuteAsync(req);

Console.WriteLine(client.BuildUri(req));
Console.WriteLine(resp.Content);

The program sends a search with a value that needs encoding.

Console.WriteLine(client.BuildUri(req));

The BuildUri method shows the final address without sending anything. The ampersand in the value became %26, so it is not mistaken for a parameter separator; the server received the original text. The space is shown here as is because Uri prints a readable form; on the wire it is encoded.

$ dotnet run
http://localhost:5060/search?q=rest sharp %26 friends&page=2
{"q":"rest sharp & friends","page":2}

C# RestSharp HEAD request

The HTTP HEAD method requests the headers that are returned if the specified resource would be requested with an HTTP GET method, but without its body.

Program.cs
using RestSharp;

using var client = new RestClient("http://localhost:5060");

var req = new RestRequest("head", Method.Head);
RestResponse resp = await client.ExecuteAsync(req);

Console.WriteLine($"{(int)resp.StatusCode} body length: {resp.Content?.Length ?? 0}");

foreach (var header in resp.ContentHeaders!)
{
    Console.WriteLine(header);
}

foreach (var header in resp.Headers!.Where(h => h.Name == "Server" || h.Name == "Date"))
{
    Console.WriteLine($"{header.Name}={(header.Name == "Date" ? "..." : header.Value)}");
}

We generate a HEAD request to a resource and print the returned headers.

var req = new RestRequest("head", Method.Head);
RestResponse resp = await client.ExecuteAsync(req);

The method is the second argument of RestRequest. We run it with the general ExecuteAsync method; there are also the shortcuts ExecuteGetAsync, ExecutePostAsync, and so on, which fix the method.

foreach (var header in resp.ContentHeaders!)
{
    Console.WriteLine(header);
}

The response has two header collections. Headers holds the general and the response headers, such as Server, and ContentHeaders holds the headers that describe the content, such as Content-Type and Content-Length. The body is empty for HEAD.

$ dotnet run
200 body length: 0
Content-Type=application/json; charset=utf-8
Date=...
Server=Kestrel

C# RestSharp User-Agent and headers

The User-Agent request header is a string that lets servers and network peers identify the application, operating system, vendor, and version of the requesting user agent. The same mechanism is used for any other header.

Program.cs
using RestSharp;
using RestSharp.Authenticators;

var options = new RestClientOptions("http://localhost:5060")
{
    UserAgent = "C# console program"
};

using var client = new RestClient(options);

Console.WriteLine((await client.ExecuteAsync(new RestRequest("ua"))).Content);

// a header for one request only
var req = new RestRequest("ua").AddHeader("User-Agent", "another agent");
Console.WriteLine((await client.ExecuteAsync(req)).Content);

// default headers for all requests
client.AddDefaultHeader("X-Api-Key", "abc123");

// bearer authentication
var unauthorized = await client.ExecuteAsync(new RestRequest("secure"));
Console.WriteLine($"{(int)unauthorized.StatusCode} {unauthorized.StatusCode}");

var authOptions = new RestClientOptions("http://localhost:5060")
{
    Authenticator = new JwtAuthenticator("secret")
};

using var authClient = new RestClient(authOptions);
var ok = await authClient.ExecuteAsync(new RestRequest("secure"));
Console.WriteLine($"{(int)ok.StatusCode} {ok.Content}");

The program sets the User-Agent header in several ways and uses bearer authentication.

var options = new RestClientOptions("http://localhost:5060")
{
    UserAgent = "C# console program"
};

Client-wide settings are collected in RestClientOptions. The UserAgent property sets the default user agent of the client.

var req = new RestRequest("ua").AddHeader("User-Agent", "another agent");

AddHeader adds a header to a single request. The server sees both values, because the header is added to the one set by the options, not substituted for it. Headers for all requests of the client are set with AddDefaultHeader.

Authenticator = new JwtAuthenticator("secret")

Authenticators add credentials to every request. JwtAuthenticator sends the token in the Authorization: Bearer header. There are also HttpBasicAuthenticator and OAuth authenticators.

$ dotnet run
C# console program
another agent C# console program
401 Unauthorized
200 "welcome"

C# RestSharp POST JSON

We post JSON data with the ExecutePostAsync and PostAsync methods. We also use PUT and DELETE.

Program.cs
using RestSharp;

using var client = new RestClient("http://localhost:5060");

// POST a JSON body: the object is serialized for us
var post = new RestRequest("todos").AddJsonBody(new { title = "learn RestSharp" });
RestResponse created = await client.ExecutePostAsync(post);

Console.WriteLine($"{(int)created.StatusCode} {created.StatusCode}");
Console.WriteLine(created.Content);
Console.WriteLine(created.Headers!.First(h => h.Name == "Location").Value);

// the typed shortcut
Todo? todo = await client.PostAsync<Todo>(new RestRequest("todos").AddJsonBody(new NewTodo("second")));
Console.WriteLine(todo);

// PUT and DELETE
var put = new RestRequest("todos/1", Method.Put).AddJsonBody(new NewTodo("changed"));
Console.WriteLine((await client.ExecuteAsync(put)).Content);

var del = await client.ExecuteAsync(new RestRequest("todos/1", Method.Delete));
Console.WriteLine($"{(int)del.StatusCode} {del.StatusCode}");

record Todo(int Id, string Title, bool Completed);
record NewTodo(string Title);

The program creates, changes, and deletes todo items.

var post = new RestRequest("todos").AddJsonBody(new { title = "learn RestSharp" });

We pass an object to AddJsonBody, and RestSharp serializes it and sets the Content-Type to application/json. Do not pass a string that is already JSON; the body would then be serialized again as a JSON string.

RestResponse created = await client.ExecutePostAsync(post);

The response gives access to the status code, 201 Created, and to the Location header of the new resource.

Todo? todo = await client.PostAsync<Todo>(new RestRequest("todos").AddJsonBody(new NewTodo("second")));

The typed PostAsync sends the request and deserializes the response in one call.

var put = new RestRequest("todos/1", Method.Put).AddJsonBody(new NewTodo("changed"));
var del = await client.ExecuteAsync(new RestRequest("todos/1", Method.Delete));

For the other methods, we give the Method to the request and use ExecuteAsync. A successful DELETE answers with 204 No Content and no body.

$ dotnet run
201 Created
{"id":3,"title":"learn RestSharp","completed":false}
/todos/3
Todo { Id = 4, Title = second, Completed = False }
{"id":1,"title":"changed","completed":true}
204 NoContent

C# RestSharp form data and file upload

Parameters added with AddParameter to a POST request are sent as an application/x-www-form-urlencoded form. A file is added with AddFile, and the request becomes multipart/form-data.

Program.cs
using RestSharp;

using var client = new RestClient("http://localhost:5060");

// URL-encoded form
var form = new RestRequest("form", Method.Post)
    .AddParameter("name", "John Doe")
    .AddParameter("occupation", "gardener");

Console.WriteLine((await client.ExecuteAsync(form)).Content);

// multipart file upload
File.WriteAllText("hello.txt", "hello from a file");

var upload = new RestRequest("upload", Method.Post)
    .AddFile("file", "hello.txt")
    .AddParameter("comment", "a small file");
upload.AlwaysMultipartFormData = true;

var resp = await client.ExecuteAsync(upload);
Console.WriteLine(resp.Content);

The program posts a form and uploads a small file.

upload.AlwaysMultipartFormData = true;

The setting forces the multipart format, which the endpoint expects. A request with a file uses it anyway; it matters for requests with only plain parameters.

$ dotnet run
{"name":"John Doe","occupation":"gardener"}
{"fileName":"hello.txt","length":17,"content":"hello from a file"}

C# RestSharp error handling

By default, RestSharp does not throw an exception for an HTTP error status such as 404 or 500. The response tells us what happened: IsSuccessful is true for the 2xx statuses, StatusCode has the HTTP status, and ErrorException holds the exception for a failure. Network problems, such as a refused connection or a timeout, are reported in the same way, with the ResponseStatus property.

Program.cs
using RestSharp;

using var client = new RestClient("http://localhost:5060");

// HTTP errors do not throw by default
var resp = await client.ExecuteAsync(new RestRequest("todos/99"));

Console.WriteLine($"{(int)resp.StatusCode} {resp.StatusCode}");
Console.WriteLine($"IsSuccessful={resp.IsSuccessful}, ErrorException={resp.ErrorException?.GetType().Name}");

// the typed Get returns null for 404
Todo? none = await client.GetAsync<Todo>("todos/99");
Console.WriteLine(none is null);

// we decide what to do with a failed status
if (!resp.IsSuccessful)
{
    Console.WriteLine($"request failed: {resp.ErrorException?.Message}");
}

// network problems are reported in the response
using var unreachable = new RestClient("http://localhost:1");
var failed = await unreachable.ExecuteAsync(new RestRequest("x"));
Console.WriteLine($"{failed.ResponseStatus}: {failed.ErrorException?.GetType().Name}");

record Todo(int Id, string Title, bool Completed);

The program provokes an HTTP error and a network error.

Todo? none = await client.GetAsync<Todo>("todos/99");

The typed GetAsync returns null for 404, which is convenient for "not found" as an expected case. Other failures, such as 500, throw an HttpRequestException from this typed method.

using var unreachable = new RestClient("http://localhost:1");
var failed = await unreachable.ExecuteAsync(new RestRequest("x"));

Nothing listens on port 1, so the connection is refused. The call does not throw; the response has ResponseStatus.Error and the exception.

$ dotnet run
404 NotFound
IsSuccessful=False, ErrorException=HttpRequestException
True
request failed: Request failed with status code NotFound
Error: HttpRequestException

C# RestSharp timeout, cancellation and retries

Requests to remote services can be slow or fail temporarily, so we should limit the waiting time. The timeout is set in the options, a cancellation token limits a single call, and a loop retries transient failures.

Program.cs
using RestSharp;

var options = new RestClientOptions("http://localhost:5060")
{
    Timeout = TimeSpan.FromSeconds(1)
};

using var client = new RestClient(options);

var resp = await client.ExecuteAsync(new RestRequest("slow"));
Console.WriteLine($"{resp.ResponseStatus}: {resp.ErrorException?.GetType().Name}");

// a cancellation token for a single call
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
using var client2 = new RestClient("http://localhost:5060");

try
{
    await client2.ExecuteAsync(new RestRequest("slow"), cts.Token);
}
catch (OperationCanceledException)
{
    Console.WriteLine("canceled");
}

// a simple retry loop for transient errors
for (int attempt = 1; attempt <= 3; attempt++)
{
    var r = await client2.ExecuteAsync(new RestRequest("flaky").AddQueryParameter("n", attempt));
    Console.WriteLine($"attempt {attempt}: {(int)r.StatusCode}");

    if (r.IsSuccessful)
    {
        break;
    }

    await Task.Delay(100 * attempt);
}

The program calls an endpoint that needs three seconds, and one that fails at first.

var options = new RestClientOptions("http://localhost:5060")
{
    Timeout = TimeSpan.FromSeconds(1)
};

The timeout applies to every request of the client. When it expires, the response reports ResponseStatus.TimedOut.

await client2.ExecuteAsync(new RestRequest("slow"), cts.Token);

The second argument is a cancellation token. When it is cancelled, the call throws an OperationCanceledException, which we catch.

await Task.Delay(100 * attempt);

The retry loop waits longer after every failure (a simple backoff) and gives up after three attempts. Only retry requests that are safe to repeat, such as GET; retrying a POST may create duplicates. For production code, a library such as Polly is a better fit, or the resilience handlers of Microsoft.Extensions.Http.

$ dotnet run
TimedOut: TaskCanceledException
canceled
attempt 1: 503
attempt 2: 200

C# RestSharp with a public API

The same code works against any REST API on the internet. Here we call the public test API jsonplaceholder.typicode.com over HTTPS.

Program.cs
using RestSharp;

// RestClient is thread-safe and meant to be reused: create it once
var client = new RestClient("https://jsonplaceholder.typicode.com");

var todo = await client.GetAsync<Todo>("todos/3");
Console.WriteLine(todo);

var resp = await client.ExecuteAsync(new RestRequest("todos/3"));
Console.WriteLine(resp.ResponseUri);

record Todo(int UserId, int Id, string Title, bool Completed);

The client is created once. RestClient is thread-safe and wraps an HttpClient, so it should be reused for the lifetime of the application, or registered in the dependency injection container, and not created per request. The ResponseUri property shows the final address, after redirects.

$ dotnet run
Todo { UserId = 1, Id = 3, Title = fugiat veniam minus, Completed = False }
https://jsonplaceholder.typicode.com/todos/3

Source

RestSharp documentation

In this article we have used the RestSharp library to create HTTP requests.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.