In today's interconnected world, integrating with external APIs is a common requirement for many software projects. Whether you're building a web application, mobile app, or any other software that needs to communicate with external services, understanding how to make API POST requests with JSON data and authentication tokens in a C# class library can be incredibly valuable. In this blog post, we'll walk you through the process of creating a C# class library that can be used as a reference for making such requests.
Step 1: Create a C# Class Library Project
To create a C# class library project in Visual Studio that compiles into a .dll (Dynamic-Link Library) file, you can follow these steps:
1. Open Visual Studio:
If you don't have Visual Studio installed, you can download the Community edition for free from the official Microsoft website.
2. Create a New Project:
Go to "File" > "New" > "Project..."
In the "Create a new project" window, search for "Class Library" or "Class Library (.NET Core)" depending on the version of .NET you want to target.
Select the appropriate project template and click "Next."
Add the below C# code:
-----------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
namespace CSharpAPIClassLibrary
{
public class AXApiService
{
private readonly HttpClient httpClient;
public AXApiService(string baseUri)
{
httpClient = new HttpClient { BaseAddress = new Uri(baseUri) };
}
public async Task<string> PostDataAsync(string endpoint, string jsonContent, string authToken)
{
try
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(endpoint, content);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
throw new Exception($"API request failed with status code {response.StatusCode}");
}
catch (Exception ex)
{
throw new Exception($"API request failed: {ex.Message}");
}
}
}
}
-------------------------------------------------------------------------------------------------------------------------
3. Build the Project:
a)Build your class library project by clicking "Build" > "Build Solution" or using the keyboard shortcut (usually F6).
b)This action will compile your code into a .dll file.
4. Locate the .dll File:
a)The compiled .dll file can be found in the "bin" folder of your project. By default, it's in a subfolder named after your target framework (e.g., "bin\Debug\netstandard2.0" for a .NET Standard 2.0 project).
Your C# class library is now compiled into a .dll file and is ready to be used in other projects or applications. You can reference this .dll in other C# projects, such as console applications, Windows Forms applications, ASP.NET applications, or any other .NET application type.
Note:
This ApiClient class allows you to set the base URL, make POST requests with JSON payloads, and include an authentication token in the headers.
Step 2: Use the API Client in Your Application
a)To use this library in an Application Object Tree (AOT) project, add a reference to your class library by right-clicking on the AOT project, selecting "Add Reference," and then browsing for your class library's DLL file in the bin/Debug (or bin/Release) folder of your class library project.
b)In your AOT project, you can now use the ApiService class to make API calls with the desired content type and authorization token.
Here's an example of how you can use this class in your AOT project:
using CSharpAPIClassLibrary;
internal final class CallCshrpLibAPIPostEmp
{
/// <summary>
/// Class entry point. The system will call this method when a designated menu
/// is selected or when execution starts and this class is set as the startup class.
/// </summary>
/// <param name = "_args">The specified arguments.</param>
public static void main(Args _args)
{
var axApiService = new AXApiService("https://api.example.com"); // Base URL
str endpoint = "/api/resource"; //endPoint POST URL
str jsonContent = "{ \"key\": \"value\" }";
str authToken = = "your-auth-token";
try
{
str response = axApiService.PostDataAsync(endpoint, jsonContent, authToken).Result;
info("API response: " + response);
}
catch (Exception::Error)
{
// Handle exceptions that may occur during the request
error("An error occurred during the HTTP request.");
}
}
}
You've now created a C# class library that can be used as a reference for making API POST requests with JSON data and authentication tokens. This library can be reused in various C# applications, making it easier to integrate with external APIs securely and efficiently.
Remember to handle errors and edge cases according to your application's specific requirements and consult the API's documentation for any additional details. Happy coding! ---Mallik
No comments:
Post a Comment