In this tutorial, we'll build a simple C# Windows Forms application that connects to a REST API. Our goal is to interact with the
products
API endpoints we created earlier, using HTTP requests to view, add, update, and delete product records. This tutorial is beginner-friendly and demonstrates how to use HttpClient
in C# to communicate with RESTful services. Before diving into this tutorial, it's essential to complete our previous tutorial on creating a REST API using native PHP as a server-side foundation. In that guide, we built a simple REST API to manage products and categories, covering basic API endpoints like creating, updating, deleting, and retrieving product records.Prerequisites
- A basic understanding of C# and Windows Forms.
- Visual Studio installed on your machine.
- The REST API from the previous tutorial (running locally or on a server).
Project Setup
1. Create a new Windows Forms App in Visual Studio. Open Visual Studio, select Create a new project, and choose Windows Forms App (.NET Framework).ID
, Name
, Description
, and Price
, as well as buttons for CRUD operations (Get, Create, Update, Delete). Here’s a sample layout:- TextBox for
ID
- TextBox for
Name
- TextBox for
Description
- TextBox for
Price
- Buttons labeled
Get
,Create
,Update
, andDelete
- ListBox or DataGridView to display product data
Product
class to hold the product data. This class will be used to serialize and deserialize JSON.public class Product { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public decimal Price { get; set; } }
ApiResponse
Class to represent the JSON response structure. This class will be used on message handling of some responses.public class ApiResponse { public string Message { get; set; } }
Adding Code for API Calls
1. Add necessary using statements at the top of your code:using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Windows.Forms; using Newtonsoft.Json; using System.Collections.Generic;
Newtonsoft.Json
from NuGet to handle JSON serialization and deserialization.2. Initialize HttpClient. We’ll set up
HttpClient
as a static client to make HTTP requests to the API.private static readonly HttpClient client = new HttpClient();
localhost
to your API’s address if it’s running on a server).private readonly string apiUrl = "http://localhost/api/products"; //private readonly string apiUrl = "https://bcssti.com/api-sample/products/";
Implementing CRUD Operations
1. Get Products (GET)
This method fetches the list of all products from the API and displays them in a ListView or DataGridView.
private async void GetProducts() { try { var response = await client.GetAsync(apiUrl); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); var products = JsonConvert.DeserializeObject<List<Product>>(responseBody); // Display the products in a ListView or DataGridView productListBox.DataSource = products; productListBox.DisplayMember = "Name"; // Display name or other relevant info } catch (Exception ex) { MessageBox.Show($"Error: {ex.Message}"); } }
2. Get Product by ID (GET)
This method retrieves a single product based on its ID.
private async void GetProductById(int id) { try { var response = await client.GetAsync($"{apiUrl}?id={id}"); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); var product = JsonConvert.DeserializeObject<Product>(responseBody); // Populate fields with product data txtName.Text = product.Name; txtDescription.Text = product.Description; txtPrice.Text = product.Price.ToString(); } catch (Exception ex) { MessageBox.Show($"Error: {ex.Message}"); } }
3. Create Product (POST)
This method sends a new product to the API.
private async void CreateProduct() { dynamic product = new { name = txtName.Text, description = txtDescription.Text, price = decimal.Parse(txtPrice.Text) }; var json = JsonConvert.SerializeObject(product); var content = new StringContent(json, Encoding.UTF8, "application/json"); try { var response = await client.PostAsync(apiUrl, content); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(responseBody); // Display the message from the API response MessageBox.Show(apiResponse.Message ?? "Product created successfully"); } catch (Exception ex) { MessageBox.Show($"Error: {ex.Message}"); } }
4. Update Product (PUT)
This method updates an existing product.
private async void UpdateProduct(int id) { dynamic product = new { name = txtName.Text, description = txtDescription.Text, price = decimal.Parse(txtPrice.Text) }; var json = JsonConvert.SerializeObject(product); var content = new StringContent(json, Encoding.UTF8, "application/json"); try { var response = await client.PutAsync($"{apiUrl}?id={id}", content); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(responseBody); // Display the message from the API response MessageBox.Show(apiResponse.Message ?? "Product updated successfully"); } catch (Exception ex) { MessageBox.Show($"Error: {ex.Message}"); } }
5. Delete Product (DELETE)
This method deletes a product by ID.
private async void DeleteProduct(int id) { try { var response = await client.DeleteAsync($"{apiUrl}?id={id}"); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(responseBody); // Display the message from the API response MessageBox.Show(apiResponse.Message ?? "Product deleted successfully"); } catch (Exception ex) { MessageBox.Show($"Error: {ex.Message}"); } }
Testing the Application
- Run the Windows Forms App in Visual Studio.
- Use the Get button to list all products or retrieve a specific product by ID.
- Use the Create, Update, and Delete buttons to interact with the API.
This setup provides a basic client interface for the products API. You can expand this application to manage other objects or add additional features like input validation and error handling.
Final Thoughts
Creating a client for your API in C# Windows Forms is a fantastic way to learn about HTTP communication and RESTful APIs. By using HttpClient
and JSON serialization with Newtonsoft.Json
, you can quickly set up a functional application to interact with any RESTful service.
This example demonstrates only the basics, but you can extend the client with additional features:
- Pagination and Filtering: If your API supports it, implement controls for navigating through pages of data.
- Advanced Error Handling: Customize error messages for various HTTP status codes.
- UI Improvements: Use DataGridView for more complex data display and editing.
Experiment with these concepts to build a full-featured client for your REST API.