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.

 


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