C# + RestSharp - HTTP POST Request Examples in .NET
Tutorial built with .NET 7.0 and RestSharp 108.0.3
Below is a quick set of examples to show how to send HTTP POST requests from .NET to an API using the RestSharp
HTTP client which is available on NuGet.
Other RestSharp HTTP examples: GET, PUT, DELETE.
Tutorial contents
- Installing RestSharp
- Simple POST request with a JSON body
- POST request with strongly typed response
- POST request with async/await
- POST request with headers set
- POST request with error handling
Installing RestSharp from NuGet
.NET CLI: dotnet add package RestSharp
Visual Studio Package Manager Console: Install-Package RestSharp
Simple POST request with a JSON body using RestSharp
This sends an HTTP POST request to the Test JSON API which is a fake online REST API I created that includes a /products
route that responds to POST
requests with the contents of the post body plus a new id
property and createdAt
date property.
The response type is deserialized to <JsonNode>
so it can handle any dynamic properties returned in the response.
using RestSharp;
using System;
using System.Text.Json;
using System.Text.Json.Nodes;
public class Program
{
public static void Main()
{
// send POST request with RestSharp
var client = new RestClient("https://testapi.jasonwatmore.com");
var request = new RestRequest("products");
request.AddBody(new
{
name = "RestSharp POST Request Example"
});
var response = client.ExecutePost(request);
// deserialize json string response to JsonNode object
var data = JsonSerializer.Deserialize<JsonNode>(response.Content!)!;
// output result
Console.WriteLine($"""
----------------
json properties
----------------
id: {data["id"]}
createdAt: {data["createdAt"]}
----------------
raw json data
----------------
{data}
""");
}
}
Example C# app on .NET Fiddle at https://dotnetfiddle.net/LHNFuP
POST request using RestSharp with strongly typed response
This sends the same request as the above but deserializes the response to a custom Product
class that defines the expected response properties.
using RestSharp;
using System;
using System.Text.Json;
public class Program
{
public static void Main()
{
// send POST request with RestSharp
var client = new RestClient("https://testapi.jasonwatmore.com");
var request = new RestRequest("products");
request.AddBody(new
{
name = "RestSharp POST Request Example"
});
var response = client.ExecutePost(request);
// deserialize json string response to Product object
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
var product = JsonSerializer.Deserialize<Product>(response.Content!, options)!;
// output result
Console.WriteLine($"""
----------------
json properties
----------------
id: {product.Id}
name: {product.Name}
createdAt: {product.CreatedAt}
""");
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreatedAt { get; set; }
}
Example C# app on .NET Fiddle at https://dotnetfiddle.net/jcHA8u
POST request using RestSharp with async/await
This sends the same POST request from .NET using RestSharp, but this version uses an async
method and the await
C# operator to wait for the asynchronous HTTP request to complete without blocking the thread that called the async method.
using RestSharp;
using System;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
// send POST request with RestSharp
var client = new RestClient("https://testapi.jasonwatmore.com");
var request = new RestRequest("products");
request.AddBody(new
{
name = "RestSharp POST Request Example"
});
var response = await client.ExecutePostAsync(request);
// deserialize json string response to JsonNode object
var data = JsonSerializer.Deserialize<JsonNode>(response.Content!)!;
// output result
Console.WriteLine($"""
----------------
json properties
----------------
id: {data["id"]}
createdAt: {data["createdAt"]}
----------------
raw json data
----------------
{data}
""");
}
}
Example C# app on .NET Fiddle at https://dotnetfiddle.net/YZ1Ga3
POST request using RestSharp with headers set
This sends the same request again with a couple of headers set, the HTTP Authorization
header and a custom header My-Custom-Header
.
To update existing headers call the AddOrUpdateHeader()
method, e.g. request.AddOrUpdateHeader("Authorization", "Bearer my-token");
.
using RestSharp;
using System;
using System.Text.Json;
using System.Text.Json.Nodes;
public class Program
{
public static void Main()
{
// send POST request with RestSharp
var client = new RestClient("https://testapi.jasonwatmore.com");
var request = new RestRequest("products");
request.AddHeader("Authorization", "Bearer my-token");
request.AddHeader("My-Custom-Header", "foobar");
request.AddBody(new
{
name = "RestSharp POST Request Example"
});
var response = client.ExecutePost(request);
// deserialize json string response to JsonNode object
var data = JsonSerializer.Deserialize<JsonNode>(response.Content!)!;
// output result
Console.WriteLine($"""
----------------
json properties
----------------
id: {data["id"]}
createdAt: {data["createdAt"]}
----------------
raw json data
----------------
{data}
""");
}
}
Example C# app on .NET Fiddle at https://dotnetfiddle.net/ak12R7
POST request using RestSharp with error handling
This sends a POST request from .NET using RestSharp to an invalid url on the api then logs the error message to the console.
RestSharp ExecutePost()
vs Post()
There are a couple of methods to perform a POST request with RestSharp - ExecutePost()
and Post()
(plus their async and generic versions). The difference between the two is how they deal with error handling when a request fails.
In case of a failed HTTP request the ExecutePost()
method returns a RestReponse
that contains the ErrorException
, whereas the Post()
method throws an exception when a request fails except if it's a 404, so would require a try-catch
block to handle errors.
using RestSharp;
using System;
using System.Text.Json;
using System.Text.Json.Nodes;
public class Program
{
public static void Main()
{
// send POST request with RestSharp
var client = new RestClient("https://testapi.jasonwatmore.com");
var request = new RestRequest("invalid-url");
request.AddBody(new
{
name = "RestSharp POST Request Example"
});
var response = client.ExecutePost(request);
// handle error
if (!response.IsSuccessful)
{
Console.WriteLine($"ERROR: {response.ErrorException?.Message}");
return;
}
// deserialize json string response to JsonNode object
var data = JsonSerializer.Deserialize<JsonNode>(response.Content!)!;
// output result
Console.WriteLine($"""
----------------
json properties
----------------
id: {data["id"]}
createdAt: {data["createdAt"]}
----------------
raw json data
----------------
{data}
""");
}
}
Example C# app on .NET Fiddle at https://dotnetfiddle.net/TXCoDB
Need Some .NET Help?
Search fiverr for freelance .NET developers.
Follow me for updates
When I'm not coding...
Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!