Published: January 30 2023

C# + RestSharp - HTTP PUT 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 PUT requests from .NET to an API using the RestSharp HTTP client which is available on NuGet.

Other RestSharp HTTP examples: GET, POST, DELETE.

Tutorial contents


Installing RestSharp from NuGet

.NET CLI: dotnet add package RestSharp

Visual Studio Package Manager Console: Install-Package RestSharp


Simple PUT request with a JSON body using RestSharp

This sends an HTTP PUT request to the Test JSON API which is a fake online REST API that includes a product details route (/products/{id}), the route responds to PUT requests with the contents of the PUT request body plus the product id property and updatedAt 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 PUT request with RestSharp
        var client = new RestClient("https://testapi.jasonwatmore.com");
        var request = new RestRequest("products/1");
        request.AddBody(new
        {
            name = "RestSharp PUT Request Example"
        });        
        var response = client.ExecutePut(request);

        // deserialize json string response to JsonNode object
        var data = JsonSerializer.Deserialize<JsonNode>(response.Content!)!;

        // output result
        Console.WriteLine($"""
        ----------------
        json properties
        ----------------
        id: {data["id"]}
        updatedAt: {data["updatedAt"]}

        ----------------
        raw json data
        ----------------
        {data}

        ----------------
        Documentation at https://jasonwatmore.com/c-restsharp-http-put-request-examples-in-net
        """);
    }
}

Example C# app on .NET Fiddle at https://dotnetfiddle.net/BPWJTO


PUT 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 PUT request with RestSharp
        var client = new RestClient("https://testapi.jasonwatmore.com");
        var request = new RestRequest("products/1");
        request.AddBody(new
        {
            name = "RestSharp PUT Request Example"
        });        
        var response = client.ExecutePut(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}
        updatedAt: {product.UpdatedAt}
        
        ----------------
        Documentation at https://jasonwatmore.com/c-restsharp-http-put-request-examples-in-net
        """);
    }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime UpdatedAt { get; set; }
}

Example C# app on .NET Fiddle at https://dotnetfiddle.net/oqj6id


PUT request using RestSharp with async/await

This sends the same PUT 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 PUT request with RestSharp
        var client = new RestClient("https://testapi.jasonwatmore.com");
        var request = new RestRequest("products/1");
        request.AddBody(new
        {
            name = "RestSharp PUT Request Example"
        });        
        var response = await client.ExecutePutAsync(request);

        // deserialize json string response to JsonNode object
        var data = JsonSerializer.Deserialize<JsonNode>(response.Content!)!;
        
        // output result
        Console.WriteLine($"""
        ----------------
        json properties
        ----------------
        id: {data["id"]}
        updatedAt: {data["updatedAt"]}

        ----------------
        raw json data
        ----------------
        {data}

        ----------------
        Documentation at https://jasonwatmore.com/c-restsharp-http-put-request-examples-in-net
        """);
    }
}

Example C# app on .NET Fiddle at https://dotnetfiddle.net/JvJbdc


PUT 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 PUT request with RestSharp
        var client = new RestClient("https://testapi.jasonwatmore.com");
        var request = new RestRequest("products/1");
        request.AddHeader("Authorization", "Bearer my-token");
        request.AddHeader("My-Custom-Header", "foobar");
        request.AddBody(new
        {
            name = "RestSharp PUT Request Example"
        });
        var response = client.ExecutePut(request);
        
        // deserialize json string response to JsonNode object
        var data = JsonSerializer.Deserialize<JsonNode>(response.Content!)!;
        
        // output result
        Console.WriteLine($"""
        ----------------
        json properties
        ----------------
        id: {data["id"]}
        updatedAt: {data["updatedAt"]}

        ----------------
        raw json data
        ----------------
        {data}

        ----------------
        Documentation at https://jasonwatmore.com/c-restsharp-http-put-request-examples-in-net
        """);
    }
}

Example C# app on .NET Fiddle at https://dotnetfiddle.net/RjeHHz


PUT request using RestSharp with error handling

This sends a PUT request from .NET using RestSharp to an invalid url on the api then logs the error message to the console.

RestSharp ExecutePut() vs Put()

There are a couple of methods to perform a PUT request with RestSharp - ExecutePut() and Put() (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 ExecutePut() method returns a RestReponse that contains the ErrorException, whereas the Put() method throws an exception when a request fails unless 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 PUT request with RestSharp
        var client = new RestClient("https://testapi.jasonwatmore.com");
        var request = new RestRequest("invalid-url");
        request.AddBody(new
        {
            name = "RestSharp PUT Request Example"
        });        
        var response = client.ExecutePut(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"]}
        updatedAt: {data["updatedAt"]}

        ----------------
        raw json data
        ----------------
        {data}

        ----------------
        Documentation at https://jasonwatmore.com/c-restsharp-http-put-request-examples-in-net
        """);
    }
}

Example C# app on .NET Fiddle at https://dotnetfiddle.net/1EVHfM

 


Need Some .NET Help?

Search fiverr for freelance .NET developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by