WPF | Windows| Console Application | How to Call REST API in C#

In C#, HTTPClient Class provides a base class for sending HTTP requests and receiving HTTP responses from a URL. It is a supported asynchronous feature of the .NET Framework. It handles multiple concurrent requests. in this article, we will learn How to Call REST API in C#.

Create Project

  1. Open Visual Studio or VS Code
  2. Click on “Create a new Project”
  3. Select “Template”
  4. Click Next”
  5. Enter a project name and choose a location.
  6. Select target framework
  7. Click Create

Call the REST API method from the c# console Application, Windows Forms, and WPF Application, we need to install the required packages, using NuGet Package Manager.

Install-package Microsoft.AspNet.WebApi.Client 

Create Model

Create a model class named Employees.

namespace CallRESTAPI_WPF
{
    public class Employees
    {
        public int ID { get; set; }
        public string Company { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string JobTitle { get; set; }
        public string Address { get; set;}
 
    }
}

Calling REST API using Console Application

using System.Net.Http.Headers; 

namespace CSharpTutorials
{
    public static class  Program
    {
        static void Main(string[] args)
        {
            var clientResponse =  callRESTAPI(); 

            if(clientResponse.Result == null)
            {
                Console.WriteLine("Please check the Url Parameters");
            } 
        }

       public static async Task<IEnumerable<Employees>> callRESTAPI()
        {
   
            var httpClient = new HttpClient();
            var baseUrl = "https://localhost:8080/api/Employee/GetAll";
            httpClient.BaseAddress = new Uri(baseUrl);

            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            var response = httpClient.GetAsync(baseUrl).Result;

            if (response.IsSuccessStatusCode)
            {
                dynamic dataresponseobject =  response.Content.ReadAsAsync<IEnumerable<Employees>>().Result;
            
                foreach (var item in dataresponseobject)
                {
                    Console.WriteLine($"{item.Company}");
                } 
            } 
            return response.Content.ReadAsAsync<IEnumerable<Employees>>().Result;
       }
   }

Calling REST API using WPF Application

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CallRESTAPI_WPF;

namespace callRESTAPI_WPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var dataObject = callRESTAPI();
            datagridview.ItemsSource = dataObject.Result;
        }

        public static async Task<IEnumerable<Employees>> callRESTAPI()
        {
            var httpClient = new HttpClient();
            var baseUrl = "https://localhost:8080/api/Employee/GetAll";
            httpClient.BaseAddress = new Uri(baseUrl);

            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            var response = httpClient.GetAsync(baseUrl).Result;

            if (response.IsSuccessStatusCode)
            {
                var dataresponseobject = response.Content.ReadAsAsync<IEnumerable<Employees>>().Result;

                return dataresponseobject;

            }
            return response.Content.ReadAsAsync<IEnumerable<Employees>>().Result;

        }
    }
}

WPF Design Source

<Window x:Class="callRESTAPI_WPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:callRESTAPI_WPF"
        mc:Ignorable="d"
        Title="Call REST API" Height="450" Width="800" Background="#FF5C9C9A">
    <Window.Resources>
        <SolidColorBrush x:Key="GotFocusColor" Color="Green" />
        <SolidColorBrush x:Key="LostFocusColor" Color="Transparent" />
        <Style TargetType="{x:Type DataGridRow}">
            <Setter Property="Foreground" Value="#FFB3B3B3"/>
            <Setter Property="Height" Value="25"/>
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>

            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="#FF262626"/>
                </Trigger>

                <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                    <Setter Property="Background" Value="#FF383838"/>
                </Trigger>

                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="Background" Value="#FF333333"/>
                </Trigger>

                <EventTrigger RoutedEvent="DataGrid.GotFocus">
                    <BeginStoryboard>
                        <Storyboard>
                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background">
                                <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{StaticResource GotFocusColor}" />
                            </ObjectAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>

                <EventTrigger RoutedEvent="DataGrid.LostFocus">
                    <BeginStoryboard>
                        <Storyboard>
                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background">
                                <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{StaticResource LostFocusColor}" />
                            </ObjectAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="13*"/>
            <ColumnDefinition Width="126*"/>
            <ColumnDefinition Width="25.019"/>
            <ColumnDefinition Width="404.981"/>
            <ColumnDefinition Width="222*"/>
            <ColumnDefinition Width="9*"/>
        </Grid.ColumnDefinitions>
        <DataGrid x:Name="datagridview" d:ItemsSource="{d:SampleData ItemCount=5}" Margin="9,12,30,118" Grid.ColumnSpan="4" Grid.Column="1" Background="#FF4D98B4"/>

    </Grid>
</Window>

Output

How to Call REST API in C#

Calling REST API using Windows Form

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CallRESTAPI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var clientResponse = callRESTAPI();
            if (clientResponse.Result != null)
            {
                dataGridView1.DataSource = clientResponse.Result;
            }
            else
            {
                MessageBox.Show("Data dosn't Exist");
            }
        }

        public static async Task<IEnumerable<Employees>> callRESTAPI()
        {
            var httpClient = new HttpClient();
            var baseUrl = "https://localhost:8080/api/Employee/GetAll";
            httpClient.BaseAddress = new Uri(baseUrl);

            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            var response = httpClient.GetAsync(baseUrl).Result;

            if (response.IsSuccessStatusCode)
            {
                var dataresponseobject = response.Content.ReadAsAsync<IEnumerable<Employees>>().Result;
                 
                return  dataresponseobject;
           
            }
            return response.Content.ReadAsAsync<IEnumerable<Employees>>().Result;

        } 
    }
}

Output

How to Call REST API in C#

See More ASP.NET Core | How to Call Stored Procedure in Web API without Entity Framework

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments