DEV Community

Cover image for Simplifying API Data Handling with C# Records
Sebastian Van Rooyen
Sebastian Van Rooyen

Posted on

Simplifying API Data Handling with C# Records

What Are Records in C#?

Records are a relatively new feature in C# that allow you to create immutable data types with minimal boilerplate code. Unlike traditional classes, records are designed to represent data and provide value-based equality, making them ideal for scenarios where the primary purpose of the type is to store values.

In simpler terms, a record is like a class but with some cool benefits:

  • Less Code: You don't need to write properties, constructors, or equality methods yourself.
  • Immutability: By default, records are immutable, meaning once you set their properties, they can't be changed.
  • Value Equality: Two records with the same values are considered equal, unlike classes where you typically compare object references.

For example:

public record Person(string FirstName, string LastName);
Enter fullscreen mode Exit fullscreen mode

This one liner creates a Person record with two properties, FirstName and LastName. You can now create instances of Person and compare them by their values.

var person1 = new Person("Sebastian", "Van Rooyen");
var person2 = new Person("Sebastian", "Van Rooyen");

Console.WriteLine(person1 == person2); // True
Enter fullscreen mode Exit fullscreen mode

Using Records to Fetch Data from an API

Let's see how records can be used to handle data from an API call. We'll create a simple API call using HttpClient, fetch some data, and map it to a record.

Step 1: Creating a Record for the API Response

Suppose we're calling an API that returns a user's data in JSON format like this:

{
  "id": 1,
  "name": "Sebastian Van Rooyen",
  "username": "sebastiandevelops",
  "email": "sebastiandevelops@example.com"
}
Enter fullscreen mode Exit fullscreen mode

We can create a record to represent this data:

public record User(int Id, string Name, string Username, string Email);
Enter fullscreen mode Exit fullscreen mode

Step 2: Making an API Call with HttpClient

Next, let's make an API call using HttpClient to fetch the user data. For this example, we'll assume the API endpoint is https://jsonplaceholder.typicode.com/users/1.

Here's how you can do it:

using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();

        // API call
        var response = await client.GetAsync("https://jsonplaceholder.typicode.com/users/1");

        // Ensure the response is successful
        response.EnsureSuccessStatusCode();

        // Read the response content as a string
        var jsonResponse = await response.Content.ReadAsStringAsync();

        // Deserialize the JSON string into a User record
        var user = JsonSerializer.Deserialize<User>(jsonResponse);

        // Output the user details
        Console.WriteLine($"ID: {user.Id}");
        Console.WriteLine($"Name: {user.Name}");
        Console.WriteLine($"Username: {user.Username}");
        Console.WriteLine($"Email: {user.Email}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Running the Example

When you run the code, it will output:

ID: 1
Name: Sebastian Van Rooyen
Username: sebastiandevelops
Email: sebastiandevelops@example.com
Enter fullscreen mode Exit fullscreen mode

Why Use Records for API Data?

Using records simplifies the process of mapping API data to a strongly-typed object in C#. Here's why:

  • Less Boilerplate: With records, you don't need to write constructors, GetHashCode, Equals, or ToString methods.
  • Immutability: By default, records are immutable, which is often desirable when working with data fetched from an API.
  • Value Equality: Records provide built-in value equality, making comparisons straightforward.

Records in C# offer a clean and concise way to model data, especially when working with APIs. By leveraging records, you can reduce boilerplate code, ensure immutability, and simplify your API data handling. Whether you're fetching data from a REST API or working with complex data models, records provide an elegant solution that aligns well with modern C# practices.

Top comments (0)