Published: January 27 2023

C# + RestSharp - POST a JSON Object to an API in .NET

Tutorial built with .NET 7.0 and RestSharp 108.0.3

Below is a quick example of how to POST a JSON object in an HTTP POST request from .NET to an API using the RestSharp HTTP client which is available on NuGet.


POST JSON with RestSharp

This sends an HTTP POST request to the Test JSON API which is a fake online REST API 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.

A JSON object is added to the POST request body by passing a C# object to the RestSharp method request.AddBody().

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


More RestSharp Examples

For more RestSharp POST examples see C# + RestSharp - HTTP POST Request Examples in .NET.

 


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

Other than coding...

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.


Need Some .NET Help?

Search fiverr to find help quickly from experienced .NET developers.



Supported by