Avery Delanfield
Avery Delanfield

Reputation: 23

Simple C# API Get Request with Auth credentials?

I am a beginner with C# programming. I have experience with Python, and this is essentially what I am trying to replicate with C#.

import requests, json

api_user = "[email protected]"
api_key = "keyexample"
url = "https://api.example.com/"

response = requests.get(url, auth=(api_user, api_key))
json_response = response.json()

print(json_response)

What would that code look like? Thanks

Upvotes: 0

Views: 3386

Answers (1)

Roberson Liou
Roberson Liou

Reputation: 126

You can use HttpClient library to connect with your api server. Here is the sample code with api basic authentication. Make sure to call Dispose() in the end, or you may get some GC issues.

public static class Program
    {
        public static async Task Main(string[] args)
        {
            var apiUser = "[email protected]";
            var apiKey = "keyexample";
            var url = "https://api.example.com/";

            var client = new HttpClient();
            client.BaseAddress = new Uri("https://api.example.com/");

            var authToken = Encoding.ASCII.GetBytes($"{apiUser}:{apiKey}");
            client.DefaultRequestHeaders.Authorization = 
                new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
            var response = await client.GetAsync(url);
            var content = response.Content;
            client.Dispose();
        }
    }

Upvotes: 1

Related Questions