SMT
SMT

Reputation: 469

Call REST API from C#

I have a REST based API developed in JAVA. Now I am trying to call that API from a console based C# application i.e. from it's main function. I want to know is it possible to do that. I have tried something but its not working

//I have written the below code in my class file. But the I can't find the RestClient class. What do I need to include this

static void Main(string[] args)
        {
             {

                 string endPoint = @"http:\\myRestService.com\api\";
                 var client = new RestClient(endPoint);
                 var json = client.MakeRequest();
              }
         }

Upvotes: 2

Views: 28608

Answers (1)

Thorarins
Thorarins

Reputation: 1904

From the documentation on asp.net site. this shows how it is done in C# , RestClient you tried to use is a lib, that encapsulate something like this sample. RestClient can be added as a nugget package.

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

namespace ProductStoreClient
{
    class Product
    {
        public string Name { get; set; }
        public double Price { get; set; }
        public string Category { get; set; }
    }

    class Program
    {
        static void Main()
        {
            RunAsync().Wait();
        }

        static async Task RunAsync()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:9000/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // HTTP GET
                HttpResponseMessage response = await client.GetAsync("api/products/1");
                if (response.IsSuccessStatusCode)
                {
                    Product product = await response.Content.ReadAsAsync<Product>();
                    Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
                }

                // HTTP POST
                var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
                response = await client.PostAsJsonAsync("api/products", gizmo);
                if (response.IsSuccessStatusCode)
                {
                    Uri gizmoUrl = response.Headers.Location;

                    // HTTP PUT
                    gizmo.Price = 80;   // Update price
                    response = await client.PutAsJsonAsync(gizmoUrl, gizmo);

                    // HTTP DELETE
                    response = await client.DeleteAsync(gizmoUrl);
                }
            }
        }
    }
}

Upvotes: 8

Related Questions