How to make POST requests to a REST API endpoint using C#

Last updated on 27th March 2023

This is a continuation of my previous post where I explained how to make GET requests to a REST API endpoint . This article describes how to make a POST request to a REST API endpoint from a console application in C#. The C# program below sends an HTTP POST request to a REST API endpoint to create a new user. The program uses the HttpClient class to send the request and the JsonSerializer class to serialize the user object to JSON. The endpoint we are using in this example is https://httpbin.org/post which is a fake REST API server which will accept the request and echoes it back.

Making POST Requests to a REST API Endpoint

using System;
using System.Text;
using System.Text.Json;
using System.Net.Http;
using System.Threading.Tasks;

string url = $"https://httpbin.org/post";
User newUser = new User { id = 100, 
                name = "John Luther",
                username = "John.Luther",
                email="john.luther@example.com" };
await CreateUser(url, newUser);

/// <summary>
/// This asynchronous method sends a POST request to
/// a REST API endpoint to create a new user.
///</summary>
static async Task<bool> CreateUser(string endPoint, User user)
{
    try
    {
        using var client = new HttpClient();
        var json = JsonSerializer.Serialize(user);
        HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
        var response = await client.PostAsync(endPoint, content);
        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
            return true;
        }
        else
        {
            Console.WriteLine($"Failed with status code {response.StatusCode}");
            return false;
        }

    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
        return false;
    }

}

/// <summary>
/// Class that defines a user
/// </summary>
class User
{
   public int id { get; set; }
   public string name { get; set; } = string.Empty;
   public string username { get; set; } = string.Empty;
   public string email { get; set; } = string.Empty;
}

Note: This program uses Top-Level statements and therefore requires C# 10 compiler which is included with .NET 6 and later.

Program Explanation

The program defines a User class with four properties: id, name, username, and email. It creates a new User object with some values and passes it to the CreateUser method along with the API endpoint URL.

The CreateUser method serializes the User object to JSON using the JsonSerializer class, creates an HttpContent object with the JSON data and sets the content type to "application/json"

The program sends the HTTP POST request to the specified API endpoint using the PostAsync method of the HttpClient object. The method then awaits the response and checks if it was successful. If the response was successful, it prints the response content to the console and returns true. Otherwise, it prints the status code to the console and returns false.

Here is a sample output when you run this program.

{
  "args": {}, 
  "data": "{"id":100,"name":"John Luther","username":"John.Luther","email":"john.luther@example.com"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Content-Length": "90", 
    "Content-Type": "application/json; charset=utf-8", 
    "Host": "httpbin.org", 
    "X-Amzn-Trace-Id": "Root=1-6421e344-47fa78962e744e6e0a95f640"
  }, 
  "json": {
    "email": "john.luther@example.com", 
    "id": 100, 
    "name": "John Luther", 
    "username": "John.Luther"
  }, 
  "origin": "90.113.215.71", 
  "url": "https://httpbin.org/post"
}

Overall, this program is an example of how to send an HTTP POST request to a REST API endpoint to create a new user using C# and the HttpClient class.


Post a comment

Comments

Nothing yet..be the first to share wisdom.