C# Sample code to call API without using external library

Sure! Here’s a simple sample C# code snippet to call an API without using an external library:

using System; using System.IO; using System.Net; class Program { static void Main() { // URL of the API endpoint string apiUrl = "https://api.example.com/endpoint"; // Create a WebRequest object to send the HTTP request WebRequest request = WebRequest.Create(apiUrl); // Set the request method to GET request.Method = "GET"; try { // Get the response from the API using (WebResponse response = request.GetResponse()) { // Read the response data using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream)) { string responseData = reader.ReadToEnd(); Console.WriteLine(responseData); } } } } catch (WebException ex) { // Handle any exceptions that occur during the API call Console.WriteLine("Error: " + ex.Message); } } }
Code language: JavaScript (javascript)

In this code, we use the WebRequest class from the System.Net namespace to create an HTTP request and call the API. We set the request method to “GET” and then retrieve the response from the API. The response data is read using a StreamReader, and the retrieved data is printed to the console.

Note that this code handles basic API calls without any authentication or complex headers. If your API requires authentication or additional headers, you’ll need to modify the code accordingly.

Leave a Reply