using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Newtonsoft.Json; class Program { static async Task Main(string[] args) { string url = "https://api.github.com/users/octocat"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); GitHubUser user = JsonConvert.DeserializeObject<GitHubUser>(responseBody); Console.WriteLine(user.name + " - " + user.bio); } else { Console.WriteLine("Error: " + response.ReasonPhrase); } } } } class GitHubUser { public string name { get; set; } public string bio { get; set; } }This example makes a GET request to the GitHub API to retrieve information about the
octocat
user, processes the response, and outputs the user’s name and bio to the console. The following steps are performed:
- Define a string variable
url
with the URL of the GitHub API endpoint for theoctocat
user.- Use the
HttpClient
class to create a new HTTP client object.- Set the
Accept
header of the client object to indicate that we want to receive JSON data.- Use the
GetAsync()
method of the client object to send a GET request to the API endpoint and retrieve aHttpResponseMessage
object.- Check if the response was successful using the
IsSuccessStatusCode
property of theHttpResponseMessage
object.- If the response was successful, use the
ReadAsStringAsync()
method of theHttpContent
object returned by theContent
property of theHttpResponseMessage
object to retrieve the response body as a string.- Use the
JsonConvert.DeserializeObject()
method to deserialize the JSON response into aGitHubUser
object.- Output the
name
andbio
properties of theGitHubUser
object to the console usingConsole.WriteLine()
.- If the response was not successful, output an error message to the console using
Console.WriteLine()
.Note that there are many other types of APIs you can work with, such as SOAP APIs and OAuth APIs, as well as many other types of operations you can perform, such as making POST requests, sending headers, and handling errors. This example is just one possible multi-step process for working with APIs.