Send a request to a restapi with json

Claude Larocque 666 Reputation points
2023-02-14T14:40:03.27+00:00

Do someone knows of a sample project with forms to send request to a RestAPI with tests?

Thanks

Claude from Quebec, Canada

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,884 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,839 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Jiale Xue - MSFT 44,411 Reputation points Microsoft Vendor
    2023-02-15T06:30:26.82+00:00

    Hi @Claude Larocque ,Welcome to Q&A.

    You can use httpclient and System.Text.Json.

    Here is a winform example I wrote (.Net Framework 4.8):

    using System;
    using System.Net.Http;
    using System.Text;
    using System.Text.Json;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp2
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private async void button1_Click(object sender, EventArgs e)
            {
                try
                {
                    string url = "http://example.com/api/v1/resource";
                    HttpClient client = new HttpClient();
                    var requestData = new { key = "value" };
                    string json = JsonSerializer.Serialize(requestData);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    var response = await client.PostAsync(url, content);
                    string responseContent = await response.Content.ReadAsStringAsync();
                    MessageBox.Show(responseContent);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
    }
    
    

    There may be a lack of system.memory during operation. (Manually add it into the project)

    enter image description here

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Reza Aghaei 4,946 Reputation points MVP
    2023-02-19T02:16:09.4633333+00:00

    I have shared a step-by-step guide in stackoverflow that you can take a look: Call and Consume Rest APIs in Windows Forms

    There's also a docs article on this topic: Call a Web API From a .NET Client.

    Download the Example

    Here in this post, I'll share one of my step-by-step examples which uses an online REST API service (https://northwind.vercel.app) which allows interaction with Northwind API. This example uses HttpClient and JsonConvert to get or post data:

    User's image If you want to jump to code, without reading the step-by-steo guide, you can clone or download example from here:

    Step by step example

    1. Create a WinForms Application
    2. Add a new class call it Category.cs, and use the following code for the class:
         public class Category
         {
             public int Id {get; set;}
             public string Name {get; set;}
             public string Description {get; set;}
         }
      
    3. Drop a DataGridView on the form, let's use the default name dataGridView1.
    4. Install Newtonsoft.Json nuget package. And add the following using statements to your form:
         using System.Net.Http;
         using Newtonsoft.Json;
      
    5. Define an instance of the HttpClient, at class level:
         private static HttpClient client = new HttpClient();
      
    6. To send a GET request, for example getting list of all data, assuming you have a dataGridView1 on the from, run the following code for example in Load event handler, double click on the Form to create the load handler, and use the following code:
         private async void Form1_Load(object sender, EventArgs e)
         {
             var url = "https://northwind.vercel.app/api/categories";
             var response = await client.GetAsync(url);
             if (response.StatusCode == System.Net.HttpStatusCode.OK)
             {
                 var content = await response.Content.ReadAsStringAsync();
                 var categories = JsonConvert.DeserializeObject<List<Category>>(content);
                 dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
                 dataGridView1.DataSource = categories;
             }
         }
      
      You can also use other overloads of Get, like GetStringAsync, GetStreamAsync, and etc. But GetAsync is a more generic method allowing you to get the status code as well.
    7. To send a POST request, for example posting a new data, you can use the following code, for example in click event handler of a button or a ToolStripButton:
         private async void addToolStripButton_Click(object sender, EventArgs e)
         {
             var url = "https://northwind.vercel.app/api/categories";
             var data = new Category() { Name = "Lorem", Description = "Ipsum" };
             var jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(data);
             var requestContent = new StringContent(jsonData, Encoding.Unicode, "application/json");
             var response = await client.PostAsync(url, requestContent);
             if (response.StatusCode == System.Net.HttpStatusCode.Created)
             {
                 var content = await response.Content.ReadAsStringAsync();
                 var createdCategory = JsonConvert.DeserializeObject<Category>(content);
                 MessageBox.Show(createdCategory.Id.ToString());
             }
         }
      

    To learn more and see some best practices or see an example without JsonConvert, see my stackoverflow post: Call and Consume Rest APIs in Windows Forms.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.