Friday, 10 March 2023

Making Authenticated Requests to a REST API using API Key Authentication

 As my previous article we have seen example of basic authentication in REST api using .net, now today we get an idea about API key authentication in REST api using .net using ‘HttpClient’

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

class Program
{
static async Task Main(string[] args)
{
// Set the API endpoint URL and the API key
var url = “https://api.example.com/endpoint";
var apiKey = “my_api_key”;

// Create the HttpClient instance
var client = new HttpClient();

// Set the API Key header
client.DefaultRequestHeaders.Add(“X-API-Key”, apiKey);

// Make a GET request to the API endpoint
var response = await client.GetAsync(url);

// Get the response content as a string
var responseContent = await response.Content.ReadAsStringAsync();

// Print the response
Console.WriteLine(responseContent);
}
}

In this example, we create a HttpClient instance and set the API Key header with the Add method. We then make a GET request to the API endpoint with GetAsync and await the response. Finally, we get the response content as a string with ReadAsStringAsync and print it to the console.

No comments:

Post a Comment

AdSense

The Ultimate Guide to Interceptors: Understanding Their Power and Functionality

  The Ultimate Guide to Interceptors: Understanding Their Power and Functionality An interceptor is a service that can intercept HTTP reques...

Follow