Skip to main content

C#

C# is a modern, object-oriented language developed by Microsoft. It is widely used in enterprise applications and integrates seamlessly with the .NET framework.

tip

C# is often used for building robust, scalable APIs due to its strong typing and integration with .NET. Frameworks like ASP.NET Core and libraries like RestSharp make it easy to create and consume APIs. It is also commonly used for consuming APIs in enterprise environments & Banking applications.

Let's make a simple POST request to a hypothetical API endpoint, https://api.example.com/resource, to send JSON data.

Setting up your project​

Before making API calls in C#, ensure you have:

  1. A .NET runtime installed (e.g., .NET 6 or later).
  2. A C# editor or IDE such as Visual Studio or Visual Studio Code.
  3. The System.Net.Http namespace available (included by default in most .NET projects).

Request​

We'll use the HttpClient class to send a POST request to the API endpoint.

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

namespace ApiExample
{
class Program
{
static async Task Main(string[] args)
{
// Define the API endpoint
string url = "https://api.example.com/resource";

// Create the data to send in the POST request
var requestData = new
{
name = "John Doe",
email = "johndoe@example.com",
age = 30
};

// Serialize the data to JSON
string jsonData = JsonSerializer.Serialize(requestData);

// Create an instance of HttpClient
using HttpClient client = new HttpClient();

// Set up the content type and request body
HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

try
{
// Make the POST request
HttpResponseMessage response = await client.PostAsync(url, content);

// Ensure the response indicates success
response.EnsureSuccessStatusCode();

// Read the response content
string responseBody = await response.Content.ReadAsStringAsync();

// Output the response
Console.WriteLine("Response from the API:");
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine($"An error occurred: {e.Message}");
}
}
}
}

How it works​

  1. API Endpoint: The url variable stores the endpoint URL.
  2. Request Data: The requestData object holds the data we want to send. This is serialized into JSON format using JsonSerializer.Serialize.
  3. HttpClient: The HttpClient class manages the HTTP request.
  4. HttpContent: We create an HttpContent object with the serialized JSON, setting the Content-Type to application/json.
  5. POST Request: The PostAsync method sends the POST request with the JSON data.
  6. Error Handling: A try-catch block handles any exceptions during the request.

Response​

If the API successfully processes the request, it might return a JSON response like:

{
"status": "success",
"message": "Data received successfully",
"id": "12345"
}

This will be printed to the console by the Console.WriteLine statement.

Tips for API requests in C#​

  • Use Async/Await: Always use asynchronous methods for network requests to avoid blocking your application.
  • Headers: Add custom headers using client.DefaultRequestHeaders if required by the API.
  • Error Handling: Always handle exceptions like HttpRequestException to manage connectivity issues.
  • Serialization: Use System.Text.Json or libraries like Newtonsoft.Json for JSON processing.

With these basics, you're ready to start integrating APIs into your C# projects!