DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

Simplified URL Building and HTTP Requests with Flurl

Flurl is a library for building URLs and making HTTP calls fluently and elegantly. It allows you to create URLs, add query parameters, headers, and make HTTP requests with a fluent and expressive API. Flurl also simplifies JSON serialization and deserialization, making it ideal for integrating with REST APIs. In this example, we will use Flurl to make a GET request and deserialize the JSON response.

Libraries:

To use the Flurl library, install the following NuGet package in your project:

Install-Package Flurl.Http
Enter fullscreen mode Exit fullscreen mode

Example Code:

using Flurl.Http;
using System;
using System.Threading.Tasks;

namespace FlurlExample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Making a GET request using Flurl
            var post = await "https://jsonplaceholder.typicode.com/posts/1"
                .GetJsonAsync<Post>();

            // Displaying the data in the console
            Console.WriteLine($"Title: {post.Title}\nContent: {post.Body}");
        }
    }

    // Class to map the response
    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, we use Flurl to make a GET request directly to the API jsonplaceholder.typicode.com. The GetJsonAsync() function makes the request and automatically deserializes the JSON response into a Post class object. The code is simple and fluent, allowing the URL and request to be combined cleanly. The result is displayed in the console.

Conclusion:

Flurl simplifies URL building and HTTP requests with a fluent API that reduces repetitive code. Its integration with JSON makes working with REST APIs more efficient and convenient, allowing developers to write cleaner and more readable code.

Source code: GitHub

Top comments (0)