Short tutorial

How to connect a C# app to a REST API

One of the most useful modern C# skills is learning how to call an external API, read the returned data, and display it inside your application. In this beginner-friendly tutorial, you will use HttpClient and JSON deserialization to consume a public API.

LevelBeginner
FocusHttpClient + JSON
Project typeConnected app

What you will learn

  • Create a request with HttpClient
  • Receive JSON data from a web service
  • Map the JSON into a C# model class
  • Display the result in a Windows or console app

Step 1: Create your model class

Assume the API returns a JSON object with a title and a body. Create a class that matches the response shape.

public class Post { public int userId { get; set; } public int id { get; set; } public string title { get; set; } = string.Empty; public string body { get; set; } = string.Empty; }

Step 2: Call the API

Use HttpClient to send a GET request. Then convert the JSON response into a C# object.

using System.Net.Http; using System.Text.Json; var client = new HttpClient(); string url = "https://jsonplaceholder.typicode.com/posts/1"; string json = await client.GetStringAsync(url); Post? post = JsonSerializer.Deserialize<Post>(json); if (post != null) { Console.WriteLine(post.title); Console.WriteLine(post.body); }

Step 3: Display the data in your app

In a Windows Forms app, you could place the returned values inside labels, textboxes, or a dashboard card. In a console app, you can print them directly. The main lesson is that your C# application is now connected to an external data source.

Best practice: add error handling with try-catch and validate the response before displaying it to users.

Next improvements

  • Add a button so the user can fetch data on demand
  • Allow the user to enter an ID or keyword
  • Show multiple records in a grid or list
  • Connect to a weather, news, currency, or business API