# Flurl - The elegant way to build URLs & set query params in .Net

A common task when calling web apis or resources from code is building a URL and adding the necessary query string and parameters.

The most common, naive and frequent code that we see to achieve this is :

```csharp
var userId = 1;
var completed = true;
var someParamValue = "abc";

Uri baseAddress = new Uri("https://jsonplaceholder.typicode.com/");
Uri apiUrl = new Uri($"/todos?userId={userId}&completed={completed}" +
                $"&someParam={someParamValue}", UriKind.Relative);
```

And the typical issue with the above code is that you could accidentally miss the starting `?` or the `&` and `=` in the query parameters and create bugs; another issue is the **readability** of the code. When there is a high number of query parameters in the url, the code tends to be messy and unclean.

### [Flurl](https://flurl.dev/) to the rescue.

> Flurl is a modern, fluent, asynchronous, testable, portable, buzzword-laden URL builder and HTTP client library for .NET

Flurl adds extension methods to strings which helps us easily add path segment, set query params, set fragment, etc. in a clean and elegant manner.

#### Installing Flurl

Flurl can be installed via NuGet Package manager console as: <br/>
`PM> Install-Package Flurl`

Or via the NuGet Package manager UI:

![Installing flurl.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1614286743694/AoB1b9-vk.png)

Once installed, import the `Flurl` namespace and convert the messy URLs to more readable ones.

The initial code can now be modified and constructed with flurl as :

```csharp
using Flurl;

string url = "https://jsonplaceholder.typicode.com/"
    .AppendPathSegment("todos")
    .SetQueryParam("userId", userId)
    .SetQueryParam("completed", completed)
    .SetQueryParam("someParam", someParamValue);
```

Apart from `SetQueryParam` there's also `SetQueryParams` extension that accepts object, any collection of key-value pairs, Tuples, or a Dictionary object.

Flurl extension methods are available on `String` as well on `System.Uri`. In either case, it's easy to convert back and forth using the `ToString()` and `ToUri()` methods.

```csharp
using Flurl;

Uri url = "https://jsonplaceholder.typicode.com/"
    .AppendPathSegment("todos")
    .SetQueryParams(new
    {
        userId = userId,
        completed = completed,
        someParam = someParamValue
    })
    .ToUri();
```



Flurl provides lots of other utilities and extension methods too. Do check out [flurl documentation](https://flurl.dev/docs/fluent-url/) for more details.

     
