Updated on
Flurl lets us consume a REST API like GitHub’s from C# with one fluent chain: we build the URL, add a header and a token, send the request and get our own objects back. Its HttpTest class then tests those calls without ever touching GitHub.
We touched on Flurl in our article A Few Great Ways to Consume RESTful API in C#. This time we go into the details, from authentication to unit tests, and the API we consume is GitHub’s.
What Is Flurl?
Flurl stands for Fluent URL. It is a .NET library that comes as two packages: Flurl, a URL builder, and Flurl.Http, an HTTP client built on top of it.
Flurl’s home page calls it “a modern, fluent, asynchronous, testable, portable, buzzword-laden URL builder and HTTP client library” and, buzzwords aside, that’s a fair summary.
Under the polished hood lies HttpClient. So every call is asynchronous, and we write it as one fluent chain: the URL, the headers, the authentication, the verb and the typed result.
Flurl also has its own testing support. HttpTest fakes and records every call our code makes, so we can test code that creates and deletes GitHub repositories without sending a single real request.
Since Flurl relies on extension methods, we can extend it with our own. It has its own configuration and error handling too.
A few of our readers recommended Flurl, and after using it, we think it’s worth a try.
Setting up Flurl
We add Flurl.Http to our project by typing Install-Package Flurl.Http -Version 4.0.2 in the package manager console, or with the .NET CLI: dotnet add package Flurl.Http --version 4.0.2. It brings the Flurl URL builder along as a dependency.
The snippets in this article go into Program.cs of a console app, with using Flurl; and using Flurl.Http; at the top, and each class goes in a file of its own.
And we’re good to go!
What does Flurl Offer?
Flurl consists of two main modules:Â URL builder and some utility methods as well as Flurl.Http, which is the main part and we’ll be using that to consume our APIs.
URL Builder
Flurl’s URL API can help you easily construct your URLs.
For example, you can do something like this to construct a complicated URL:
var url = "https://www.some-api.com"
.AppendPathSegment("endpoint")
.SetQueryParams(new
{
api_key = Environment.GetEnvironmentVariable("SOME_API_KEY"),
max_results = 20,
q = "Don't worry, I'll get encoded!"
})
.SetFragment("after-hash");
Console.WriteLine(url);
With SOME_API_KEY set to my-key, this prints:
https://www.some-api.com/endpoint?api_key=my-key&max_results=20&q=Don%27t%20worry%2C%20I%27ll%20get%20encoded%21#after-hash
The query string comes out encoded, just as the value promised. If the variable isn’t set, Flurl leaves api_key out of the URL altogether.
Flurl offers great ways to parse, encode and combine URLs. There is a list of methods you can utilize in the Fluent URL Building docs.
So that’s how you manipulate URLs with Flurl.
HTTP
Once that you have your URL neatly prepared, you can dive into Flurl’s HTTP features.
With Flurl, you can consume any REST endpoint, whether public or private. You can send GET, POST, PUT, PATCH or DELETE requests and set up headers, cookies and much more.
All responses are awaitable, and we get them strongly typed with GetJsonAsync<T>(). Flurl 4.0 dropped the methods that returned dynamic from Flurl.Http, and they live on only in the Flurl.Http.Newtonsoft companion package.
Flurl works well with strings, bytes, streams or any other media type, and we can return either an IFlurlResponse, which wraps the HttpResponseMessage, or the data from its body.
We’ll get to that in the examples section.
Configuration
Let’s get on with the configuration.
Now, the configuration of Flurl is available at different levels. While most people don’t need to configure their applications and are pretty much satisfied with the default library behavior, there are different levels of configuration in Flurl that will let you mold it exactly how you like it.
The stuff you can configure:
- Client settings
- Request settings
- Test settings, on
HttpTest - The
HttpClientand its message handlers - Serializers (System.Text.Json by default since Flurl 4.0)
- The client caching strategy
As we mentioned, it’s highly unlikely that you’ll need to configure some of these settings, especially if you are not sure what they do. This goes beyond the scope of this article and it can be a whole topic to itself.
But this goes to show just how powerful Flurl can be despite the simplistic view on the surface.
Eventing
Besides these settings, Flurl provides a way to decouple our business logic from Flurl itself through its event handlers. There are four events (BeforeCall, AfterCall, OnError and OnRedirect), and each handler receives a FlurlCall with the request, the response and the exception, if there is one.
The official docs show how to handle errors in one place with an event (very useful). Here it is, registered for every call we make straight from a URL string:
FlurlHttp.Clients.WithDefaults(builder => builder.OnError(HandleFlurlErrorAsync));
async Task HandleFlurlErrorAsync(FlurlCall call)
{
await Console.Error.WriteLineAsync(call.Exception.Message);
call.ExceptionHandled = true;
}
Setting ExceptionHandled to true stops the exception from bubbling up to our code, so while this handler is registered, a catch around those calls never sees it.
Once we start changing settings all over the place, Settings.ResetDefaults() puts them back to their default values. It doesn’t touch event handlers, though: an OnError handler stays attached.
Extensibility
Since Flurl is fluent by nature, which means it uses extension methods, we can add our own extensions as well if needed.
You can extend both the Url builder and Flurl.Http parts of the Flurl library.
Let’s extend the Url builder with a static class of our own:
using Flurl;
namespace FlurlExamples;
public static class UrlExtensions
{
public static Url DoMyUrlThing(this Url url)
{
// do something interesting with url
return url;
}
}
With using FlurlExamples; at the top of Program.cs, we can now do something like this:
var endpointUrl = "https://api.github.com/"
.AppendPathSegment("endpoint")
.DoMyUrlThing(); // uses the Url extension
Pretty slick.
We can also extend the Flurl.Http part. Flurl.Http’s own chainable methods come in sets of four overloads (for string, Url, System.Uri and IFlurlRequest), and we’ll write three of them:
using Flurl;
using Flurl.Http;
namespace FlurlExamples;
public static class RequestExtensions
{
public static IFlurlRequest DoMyThing(this IFlurlRequest req)
{
// do something interesting with req.Settings, req.Headers, req.Url, etc.
return req;
}
public static IFlurlRequest DoMyThing(this Url url) => new FlurlRequest(url).DoMyThing();
public static IFlurlRequest DoMyThing(this string url) => new FlurlRequest(url).DoMyThing();
}
And then, our method is available through the fluent interface as a string, Url or IFlurlRequest extension:
var response = await "https://api.github.com"
.DoMyThing() // string extension
.GetAsync();
response = await "https://api.github.com"
.AppendPathSegment("endpoint")
.DoMyThing() // Url extension
.GetAsync();
response = await "https://api.github.com"
.AppendPathSegment("endpoint")
.WithBasicAuth("username", "password")
.DoMyThing() // IFlurlRequest extension
.GetAsync();
If you are unfamiliar with extension methods, check out our tutorial about them.
Two Ways To Authenticate in Flurl
Of course, many APIs hide confidential resources behind protected endpoints. To get to that endpoints you need to have certain rights (authorization), and you do that by authenticating yourself.
Flurl offers two ways of authenticating: Basic Authentication and OAuth 2.0 bearer token.
Here’s how we do it:
await "https://api.github.com/user".WithBasicAuth("username", "password").GetAsync();
await "https://api.github.com/user".WithOAuthBearerToken("mytoken").GetAsync();
A very easy and intuitive way to authenticate!
GitHub doesn’t accept a username and password for its REST API. Its docs put it plainly: “Authentication with username and password is not supported.” So in this article we authenticate with a personal access token and send it as a bearer token. Basic Authentication still works with APIs that accept it.
The important thing to note here is that we keep the token in an environment variable, GITHUB_TOKEN. You should never, ever, store sensitive information in your code or configuration files. That’s a serious security risk!
How to Write Get, Post, Put/Patch, and Delete Requests
Now to the main event, writing requests in Flurl.
This is where Flurl really shines. Fluent syntax, combined with the asynchronous execution and readability to match it really does the job.
Our requests share a few constants:
namespace FlurlExamples.Constants;
public static class RequestConstants
{
public const string BaseUrl = "https://api.github.com/";
public const string UserAgent = "User-Agent";
public const string UserAgentValue = "Flurl";
}
GitHub rejects any request without a User-Agent header, so every call in our request handler sends one.
GitHub’s JSON uses snake_case names like full_name and html_url. Flurl 4 deserializes with System.Text.Json, so our Repository model maps them with [JsonPropertyName]:
using System.Text.Json.Serialization;
namespace FlurlExamples.Model;
public class Repository
{
[JsonPropertyName("name")]
public string? Name { get; set; }
[JsonPropertyName("full_name")]
public string? FullName { get; set; }
[JsonPropertyName("description")]
public string? Description { get; set; }
[JsonPropertyName("html_url")]
public string? Url { get; set; }
[JsonPropertyName("private")]
public bool Private { get; set; }
}
This is the line that breaks when we upgrade from Flurl 3. Newtonsoft’s [JsonProperty] attributes, which the original version of this sample used, have no effect on System.Text.Json. Flurl’s default options ignore case, so Name still fills in, but FullName comes back null and Url picks up GitHub’s url field, the API address, instead of html_url. The compiler doesn’t complain and nothing throws, so the wrong values are easy to miss.
The handler implements a small interface, one method per call:
using Flurl.Http;
using FlurlExamples.Model;
namespace FlurlExamples;
public interface IRequestHandler
{
Task<List<Repository>> GetPublicRepositories(string user);
Task<List<Repository>> GetRepositories();
Task<Repository> CreateRepository(string user, string repository);
Task<Repository> EditRepository(string user, string repository);
Task<IFlurlResponse> DeleteRepository(string user, string repository);
}
Let’s see what it looks like in our example (we use a GitHub token here):
using Flurl;
using Flurl.Http;
using FlurlExamples.Constants;
using FlurlExamples.Model;
namespace FlurlExamples;
public class FlurlRequestHandler : IRequestHandler
{
private readonly string? _githubToken;
public FlurlRequestHandler()
{
// keep secrets in environment variables, never in code or a public repo
_githubToken = Environment.GetEnvironmentVariable("GITHUB_TOKEN");
}
public async Task<List<Repository>> GetPublicRepositories(string user)
{
var result = await RequestConstants.BaseUrl
.AppendPathSegments("users", user, "repos")
.WithHeader(RequestConstants.UserAgent, RequestConstants.UserAgentValue)
.GetJsonAsync<List<Repository>>();
return result;
}
public async Task<List<Repository>> GetRepositories()
{
var result = await RequestConstants.BaseUrl
.AppendPathSegments("user", "repos")
.WithHeader(RequestConstants.UserAgent, RequestConstants.UserAgentValue)
.WithOAuthBearerToken(_githubToken)
.GetJsonAsync<List<Repository>>();
return result;
}
public async Task<Repository> CreateRepository(string user, string repository)
{
var repo = new Repository
{
Name = repository,
FullName = $"{user}/{repository}",
Description = "Generic description",
Private = false
};
var result = await RequestConstants.BaseUrl
.AppendPathSegments("user", "repos")
.WithHeader(RequestConstants.UserAgent, RequestConstants.UserAgentValue)
.WithOAuthBearerToken(_githubToken)
.PostJsonAsync(repo)
.ReceiveJson<Repository>();
return result;
}
public async Task<Repository> EditRepository(string user, string repository)
{
var repo = new Repository
{
Name = repository,
FullName = $"{user}/{repository}",
Description = "Modified repository",
Private = false
};
var result = await RequestConstants.BaseUrl
.AppendPathSegments("repos", user, repository)
.WithHeader(RequestConstants.UserAgent, RequestConstants.UserAgentValue)
.WithOAuthBearerToken(_githubToken)
.PatchJsonAsync(repo)
.ReceiveJson<Repository>();
return result;
}
public async Task<IFlurlResponse> DeleteRepository(string user, string repository)
{
var result = await RequestConstants.BaseUrl
.AppendPathSegments("repos", user, repository)
.WithHeader(RequestConstants.UserAgent, RequestConstants.UserAgentValue)
.WithOAuthBearerToken(_githubToken)
.DeleteAsync();
return result;
}
}
GetPublicRepositories() is the one call that needs no token. It reads the public repositories of any user or organization, so we can try Flurl against GitHub right away. GitHub allows 60 unauthenticated requests an hour, though, and a token raises that to 5,000. The other four calls act on our own account, and DeleteAsync() gives us back the IFlurlResponse, so we can check its StatusCode. EditRepository() sends a PATCH request, and GitHub changes only the fields we send.
Program.cs calls these methods with using FlurlExamples; and using FlurlExamples.Model; next to the two Flurl ones at the top.
If you are unfamiliar with GitHub tokens, GitHub’s guide to managing your personal access tokens shows how to create one. A classic token needs the repo scope for these calls, and DeleteRepository() also needs delete_repo.
Exception Handling
Flurl.Http throws a FlurlHttpException whenever a response status falls outside the 2xx and 3xx range, so a 404 or a 422 lands in our catch block. From there, GetResponseJsonAsync<T>() reads an error response of a known shape, and GetResponseStringAsync() reads one of any shape.
GitHub’s errors carry a message, so a small model covers them:
using System.Text.Json.Serialization;
namespace FlurlExamples.Model;
public class GitHubError
{
[JsonPropertyName("message")]
public string? Message { get; set; }
}
Let’s see how a real-world example might look:
var flurlRequestHandler = new FlurlRequestHandler();
try
{
var newRepository = await flurlRequestHandler.CreateRepository("CodeMazeBlog", "Test-Repository");
Console.WriteLine($"Repository created: {newRepository.FullName}");
}
catch (FlurlHttpException ex)
{
// the repository already exists
// for an error of unknown shape, read await ex.GetResponseStringAsync() instead
var error = await ex.GetResponseJsonAsync<GitHubError>();
Console.WriteLine(ex.Message);
Console.WriteLine(error.Message);
}
In this scenario, we are trying to create a repository. If that repository already exists, GitHub answers with 422 Unprocessable Entity, and we catch the FlurlHttpException to figure out what happened. The exception message names the status, the verb and the URL:
Call failed with status code 422 (Unprocessable Entity): POST https://api.github.com/user/repos Repository creation failed.
We produced this output offline, with HttpTest playing GitHub’s part, which is exactly what the next section is about.
Or we can allow other status codes, so they don’t throw at all:
var repoUrl = "https://api.github.com/repos/CodeMazeBlog/flurl-examples";
await repoUrl.AllowHttpStatus(404, 409).GetAsync();
await repoUrl.AllowHttpStatus("400-404,6xx").GetAsync();
await repoUrl.AllowAnyHttpStatus().GetAsync();
How Do We Unit Test Flurl Calls With HttpTest?
Testing Flurl calls is simple right out of the box, and it all starts with the HttpTest class.
Creating an HttpTest switches Flurl into test mode. From then on, every call our code makes through Flurl is faked and recorded instead of sent. By default, each fake call gets a 200 OK with an empty body, and RespondWith() or RespondWithJson() queue the responses we want instead, error statuses included.
After the call, ShouldHaveCalled() asserts that a request went to a URL, and WithVerb(), WithHeader() and Times() narrow it down. Once we dispose of the HttpTest, Flurl sends real requests again.
There’s nothing to mock, and our handler doesn’t change to become testable. With GitHub, CreateRepository() and DeleteRepository() change a real account, and these tests never send them.
The tests live in an MSTest project that references FlurlExamples and installs Flurl.Http as well:
using Flurl;
using Flurl.Http;
using Flurl.Http.Testing;
using FlurlExamples;
using FlurlExamples.Constants;
using FlurlExamples.Model;
namespace FlurlTests;
[TestClass]
public class Tests
{
[TestMethod]
public async Task GetRepositories_ShouldHaveBeenCalled_Once()
{
using var httpTest = new HttpTest();
var flurlRequestHandler = new FlurlRequestHandler();
await flurlRequestHandler.GetRepositories();
httpTest.ShouldHaveCalled(Url.Combine(RequestConstants.BaseUrl, "user", "repos"))
.WithVerb(HttpMethod.Get)
.Times(1);
}
[TestMethod]
public async Task CreateRepository_ShouldHaveBeenCalled_Once()
{
using var httpTest = new HttpTest();
var flurlRequestHandler = new FlurlRequestHandler();
await flurlRequestHandler.CreateRepository("CodeMazeBlog", "Test");
httpTest.ShouldHaveCalled(Url.Combine(RequestConstants.BaseUrl, "user", "repos"))
.WithVerb(HttpMethod.Post)
.Times(1);
}
[TestMethod]
public async Task EditRepository_ShouldHaveBeenCalled_Once()
{
using var httpTest = new HttpTest();
var flurlRequestHandler = new FlurlRequestHandler();
await flurlRequestHandler.EditRepository("CodeMazeBlog", "Test");
httpTest.ShouldHaveCalled(Url.Combine(RequestConstants.BaseUrl, "repos", "CodeMazeBlog", "Test"))
.WithVerb(HttpMethod.Patch)
.Times(1);
}
[TestMethod]
public async Task DeleteRepository_ShouldHaveBeenCalled_Once()
{
using var httpTest = new HttpTest();
var flurlRequestHandler = new FlurlRequestHandler();
await flurlRequestHandler.DeleteRepository("CodeMazeBlog", "Test");
httpTest.ShouldHaveCalled(Url.Combine(RequestConstants.BaseUrl, "repos", "CodeMazeBlog", "Test"))
.WithVerb(HttpMethod.Delete)
.Times(1);
}
[TestMethod]
public async Task GetRepositories_ShouldReadGitHubFieldNames()
{
using var httpTest = new HttpTest();
httpTest.RespondWithJson(new[]
{
new { name = "flurl-examples", full_name = "CodeMazeBlog/flurl-examples", @private = false }
});
var flurlRequestHandler = new FlurlRequestHandler();
var repositories = await flurlRequestHandler.GetRepositories();
Assert.AreEqual("CodeMazeBlog/flurl-examples", repositories[0].FullName);
}
[TestMethod]
public async Task CreateRepository_WhenNameIsTaken_ShouldThrowFlurlHttpException()
{
using var httpTest = new HttpTest();
httpTest.RespondWithJson(new { message = "Repository creation failed." }, 422);
var flurlRequestHandler = new FlurlRequestHandler();
var ex = await Assert.ThrowsExactlyAsync<FlurlHttpException>(
() => flurlRequestHandler.CreateRepository("CodeMazeBlog", "Test"));
var error = await ex.GetResponseJsonAsync<GitHubError>();
Assert.AreEqual(422, ex.StatusCode);
Assert.AreEqual("Repository creation failed.", error.Message);
Console.WriteLine(ex.Message);
}
}
The first four tests check that each method calls the right URL with the right verb. The last two arrange a response first. GetRepositories_ShouldReadGitHubFieldNames() feeds the handler GitHub-shaped JSON and checks that full_name reaches FullName, so the serializer trap from the previous section fails a test instead of shipping. CreateRepository_WhenNameIsTaken_ShouldThrowFlurlHttpException() fakes GitHub’s 422 and prints the message we saw in the exception section.
Despite what it looks like at first, these are all fake requests, and we won’t hit any real endpoints.
Very neat!
You can write tests in any other popular testing framework for .NET as well (NUnit, xUnit…). The choice is all yours.
If you prefer the notion of setting things up and tearing them down after the tests, you can do that too:
using Flurl.Http.Testing;
using FlurlExamples;
namespace FlurlTests;
[TestClass]
public class SetupTeardownTests
{
private HttpTest _httpTest = null!;
[TestInitialize]
public void CreateHttpTest()
{
_httpTest = new HttpTest();
}
[TestCleanup]
public void DisposeHttpTest()
{
_httpTest.Dispose();
}
[TestMethod]
public async Task DeleteRepository_ShouldSendTheUserAgentHeader()
{
// Flurl is in test mode
var flurlRequestHandler = new FlurlRequestHandler();
await flurlRequestHandler.DeleteRepository("CodeMazeBlog", "Test");
_httpTest.ShouldHaveMadeACall()
.WithHeader("User-Agent", "Flurl");
}
}
In MSTest, [TestInitialize] and [TestCleanup] run before and after every test, and this one checks the User-Agent header that GitHub insists on.
Arrange and assert phases are pretty flexible too. You can pretty much execute any scenario you can think of.
As an exercise you can play around with HttpTest class more, to see what else it can do!
Flurl Lifetime
Since Flurl.Http uses HttpClient under the hood, it relies on its lifetime too.
If you’ve ever worked with HttpClient, you are probably aware that it’s recommended that you instantiate it once per application lifetime because it can easily exhaust the number of sockets available.
Flurl handles that problem for us. When we call it straight from a URL string, as in every example so far, it caches one client per combination of scheme, host and port. So every request to https://api.github.com reuses the same HttpClient instance.
FlurlClient is a wrapper around HttpClient, so consequently, it’s bound to its lifetime.
If we want more control over HttpClient instances and their lifetimes, we can create a FlurlClient ourselves (Repository is our model class from earlier):
var token = Environment.GetEnvironmentVariable("GITHUB_TOKEN");
using var cli = new FlurlClient("https://api.github.com")
.WithHeader("User-Agent", "Flurl")
.WithOAuthBearerToken(token);
await cli.Request("user", "repos").PostJsonAsync(new { name = "Test-Repository" });
var myRepositories = await cli.Request("user", "repos")
.SetQueryParam("per_page", 5)
.GetJsonAsync<List<Repository>>();
Headers we set on the client go with every request it sends.
Flurl and IoC
Dependency Injection and IoC containers play a great role in modern application development.
Flurl is well suited for dependency injection.
We don’t want to new up a FlurlClient inside our services, though. We want to inject something.
That’s where IFlurlClientCache comes in. In Flurl 4.0 it took over the job IFlurlClientFactory did in 3.x, and the official documentation recommends registering it as a singleton and injecting it into our services. It holds named clients, much like named clients with IHttpClientFactory.
So our service asks the cache for a client called GitHub:
using Flurl.Http;
using Flurl.Http.Configuration;
using FlurlExamples.Model;
namespace FlurlExamples;
public class GitHubService(IFlurlClientCache clients)
{
private readonly IFlurlClient _flurlClient = clients.Get("GitHub");
public Task<List<Repository>> GetPublicRepositories(string user) =>
_flurlClient.Request("users", user, "repos").GetJsonAsync<List<Repository>>();
}
At startup, we register the cache with that client already configured. In Program.cs, this takes two more using lines, Flurl.Http.Configuration and Microsoft.Extensions.DependencyInjection:
var services = new ServiceCollection();
services.AddSingleton<IFlurlClientCache>(_ => new FlurlClientCache()
.Add("GitHub", "https://api.github.com", builder => builder
.WithHeader("User-Agent", "Flurl")));
services.AddTransient<GitHubService>();
Now every GitHubService shares one GitHub client, and the User-Agent header GitHub requires is set in one place.
Dependency Injection is a whole topic to itself, so we won’t go any deeper into it in this article.
This should be enough if you need to register Flurl through your IoC of choice.
Conclusion
This wraps it up for our Flurl library introduction.
Flurl is a neat little library that gives us both simplicity and flexibility that we need to work comfortably with REST in our C# applications.
It is simple enough to easily learn and use, and it is extensible enough to cover some pretty complex scenarios.
So we hope this little demonstration will help you understand how Flurl works and maybe even persuade you to try it out. We will definitely use it in our newest projects that require REST communication.
To learn about more useful ways to communicate with REST endpoints, you can check our article:Â A Few Great Ways to Consume RESTful API in C#.
If you’re weighing Flurl against RestSharp or Refit, our articles cover those.
What you’ve learned in this post:
- What Flurl is and what it can do for you
- How to set it up, configure it, and extend it
- How to build URLs and write requests with Flurl
- How Flurl manages
HttpClientlifetime, and how to inject it - How to unit test your Flurl calls with
HttpTest, without sending a single request
Tested with .NET 11 (SDK 11.0.100, runtime 11.0.0) and Flurl.Http 4.0.2.






