Published: January 27 2023

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

Other RestSharp HTTP examples: POST, PUT, DELETE.

Tutorial contents


Installing RestSharp from NuGet

.NET CLI: dotnet add package RestSharp

Visual Studio Package Manager Console: Install-Package RestSharp


Simple GET request with a dynamic response using RestSharp

This sends an HTTP GET request to the Test JSON API which is a fake online REST API I created that includes a product details route (/products/{id}), the returned product includes an id and name.

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 GET request with RestSharp
        var client = new RestClient("https://testapi.jasonwatmore.com");
        var request = new RestRequest("products/1");
        var response = client.ExecuteGet(request);

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

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

        ----------------
        raw json data
        ----------------
        {data}
        """);
    }
}

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


GET 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 GET request with RestSharp
        var client = new RestClient("https://testapi.jasonwatmore.com");
        var request = new RestRequest("products/1");
        var response = client.ExecuteGet(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}
        """);
    }
}

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

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


GET request using RestSharp with async/await

This sends the same GET 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 GET request with RestSharp
        var client = new RestClient("https://testapi.jasonwatmore.com");
        var request = new RestRequest("products/1");
        var response = await client.ExecuteGetAsync(request);

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

        ----------------
        raw json data
        ----------------
        {data}
        """);
    }
}

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


GET 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 GET 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");
        var response = client.ExecuteGet(request);
        
        // deserialize json string response to JsonNode object
        var data = JsonSerializer.Deserialize<JsonNode>(response.Content!)!;
        
        // output result
        Console.WriteLine($"""
        ----------------
        json properties
        ----------------
        id: {data["id"]}
        name: {data["name"]}

        ----------------
        raw json data
        ----------------
        {data}
        """);
    }
}

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


GET request using RestSharp with error handling

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

RestSharp ExecuteGet() vs Get()

There are a couple of methods to perform a GET request with RestSharp - ExecuteGet() and Get() (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 ExecuteGet() method returns a RestReponse that contains the ErrorException, whereas the Get() 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 GET request with RestSharp
        var client = new RestClient("https://testapi.jasonwatmore.com");
        var request = new RestRequest("invalid-url");
        var response = client.ExecuteGet(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"]}
        name: {data["name"]}

        ----------------
        raw json data
        ----------------
        {data}
        """);
    }
}

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

 


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