RestSharp.RequestBuilder is a wrapper class that uses Fluent Syntax to create RestRequest objects.
$ dotnet add package RestSharp.RequestBuilderRestSharp.RequestBuilder is a .NET Standard library that provides a fluent, chainable API for constructing REST requests using RestSharp. It offers a clean, expressive syntax for building complex HTTP requests with headers, authentication, parameters, files, and request bodies—all while maintaining strong type safety and minimal surface area.
The library's primary goal is to aid in creating RestRequest objects using Fluent Syntax, reducing boilerplate and improving readability. The RequestBuilder class acts as a general-purpose wrapper for the IRestRequest object. It was created to help with projects that use the RestSharp Client to interact with third-party APIs.
Install the RestSharp.RequestBuilder NuGet package from the .NET Core CLI:
dotnet add package RestSharp.RequestBuilder
Or from the NuGet package manager:
Install-Package RestSharp.RequestBuilder
Here are the two primary ways to create a RestRequest with RestSharp.RequestBuilder:
Using the RequestBuilder constructor:
var builder = new RequestBuilder("user");
var request = builder
.SetFormat(DataFormat.Json)
.SetMethod(Method.Get)
.AddHeader("test-header", "value")
.Create();
Using the fluent extension method on RestRequest:
var request = new RestRequest().WithBuilder("user")
.SetFormat(DataFormat.Json)
.SetMethod(Method.Get)
.AddHeader("test-header", "value")
.Create();
Both approaches return a fully configured RestRequest ready for use with a RestSharp RestClient.
The library provides convenient fluent methods to add query string parameters and URL segments without manually creating Parameter objects:
// Add query parameters individually
var request = new RestRequest().WithBuilder("users")
.AddQueryParameter("page", 1)
.AddQueryParameter("limit", 50)
.AddQueryParameter("sort", "desc")
.Create();
// Add multiple query parameters at once
var request = new RestRequest().WithBuilder("users")
.AddQueryParameters(new Dictionary<string, object>
{
{ "page", 1 },
{ "limit", 50 },
{ "sort", "desc" }
})
.Create();
// Add URL segments for parameterized routes
var request = new RestRequest().WithBuilder("users/{id}/posts")
.AddUrlSegment("id", 123)
.AddQueryParameter("page", 1)
.Create();
Features:
InvariantCultureThe library provides first-class fluent authentication helpers for common HTTP authentication methods:
var request = new RestRequest().WithBuilder("api/me")
.WithBearerToken("your-bearer-token")
.Create();
var request = new RestRequest().WithBuilder("admin")
.WithBasicAuth("username", "password")
.Create();
The credentials are automatically Base64-encoded as required by the HTTP Basic authentication standard.
// Using default header name (X-API-Key)
var request = new RestRequest().WithBuilder("secure")
.WithApiKey("your-api-key")
.Create();
// Using custom header name
var request = new RestRequest().WithBuilder("secure")
.WithApiKey("your-api-key", "X-Custom-Api-Key")
.Create();
var request = new RestRequest().WithBuilder("api/protected")
.WithOAuth2("oauth2-access-token")
.Create();
Authentication Features:
ArgumentNullException for null or empty valuesThe library provides fluent convenience methods for common HTTP headers, making it easier to set standard headers without having to remember exact header names or worry about typos:
// Specify custom Accept header
var request = new RestRequest().WithBuilder("api/data")
.WithAccept("application/json")
.Create();
// Convenient shortcuts for common media types
var jsonRequest = new RestRequest().WithBuilder("api/data")
.WithAcceptJson() // Sets Accept: application/json
.Create();
var xmlRequest = new RestRequest().WithBuilder("api/data")
.WithAcceptXml() // Sets Accept: application/xml
.Create();
var request = new RestRequest().WithBuilder("api/upload")
.SetMethod(Method.Post)
.WithContentType("application/json")
.AddJsonBody(new { data = "value" })
.Create();
var request = new RestRequest().WithBuilder("api/resource")
.WithUserAgent("MyCustomClient/1.2.3")
.Create();
// For custom authorization schemes beyond Bearer/Basic
var request = new RestRequest().WithBuilder("api/protected")
.WithAuthorization("Digest", "realm=\"example.com\"")
.Create();
// You can still use the specific helpers for common schemes
var bearerRequest = new RestRequest().WithBuilder("api/me")
.WithBearerToken("token123") // Shortcut for WithAuthorization("Bearer", "token123")
.Create();
// If-Match for optimistic concurrency control
var updateRequest = new RestRequest().WithBuilder("api/resource/{id}")
.AddUrlSegment("id", "123")
.SetMethod(Method.Put)
.WithIfMatch("\"v1-abc123\"")
.AddJsonBody(new { name = "Updated Name", version = "v2" })
.Create();
// If-None-Match for efficient caching
var cacheRequest = new RestRequest().WithBuilder("api/resource/{id}")
.AddUrlSegment("id", "123")
.WithIfNoneMatch("\"v1-abc123\"")
.Create();
// Useful for CORS and tracking
var request = new RestRequest().WithBuilder("api/external")
.WithReferer("https://myapp.com/page")
.WithOrigin("https://myapp.com")
.Create();
// All header methods chain fluently
var request = new RestRequest().WithBuilder("api/items")
.WithAcceptJson()
.WithContentType("application/json")
.WithUserAgent("MyClient/1.0.0")
.WithBearerToken("mytoken")
.WithIfNoneMatch("\"abc1234\"")
.WithReferer("https://example.com/page")
.WithOrigin("https://example.com")
.AddQueryParameter("page", 1)
.Create();
Header Method Features:
ArgumentNullException for null or empty valuesThe library provides convenient shortcut methods for adding request bodies with common content types:
// Add a JSON body to the request
var request = new RestRequest().WithBuilder("api/users")
.SetMethod(Method.Post)
.AddJsonBody(new { name = "John Doe", email = "john@example.com" })
.Create();
The AddJsonBody method automatically sets the request format to DataFormat.Json and serializes the body object.
// Add an XML body to the request
var request = new RestRequest().WithBuilder("api/users")
.SetMethod(Method.Post)
.AddXmlBody(new User { Id = 1, Name = "John Doe" })
.Create();
The AddXmlBody method automatically sets the request format to DataFormat.Xml and serializes the body object.
// Add form-urlencoded data (commonly used for OAuth token requests)
var request = new RestRequest().WithBuilder("oauth/token")
.SetMethod(Method.Post)
.AddFormUrlEncodedBody(new Dictionary<string, string>
{
{ "grant_type", "password" },
{ "username", "user@example.com" },
{ "password", "secretpassword" }
})
.Create();
The AddFormUrlEncodedBody method adds each key-value pair as a form parameter (GetOrPost parameter type).
Body Method Features:
ArgumentNullException for null valuesAddJsonBody and AddXmlBody automatically set the appropriate request formatAddFormUrlEncodedBody skips null values in the dictionaryImportant: Do not mix AddJsonBody/AddXmlBody with AddFormUrlEncodedBody on the same request builder. These represent mutually exclusive ways of sending data:
AddJsonBody/AddXmlBody set a request body (serialized as JSON or XML)AddFormUrlEncodedBody adds form parameters (sent as application/x-www-form-urlencoded)Choose one approach based on your API requirements. Mixing both would create a semantically invalid request.
Note: These methods work with RestSharp's serialization pipeline. For JSON, ensure you have configured an appropriate JSON serializer (RestSharp uses System.Text.Json by default). For XML, RestSharp uses the built-in .NET XML serializer.
RestSharp.RequestBuilder implements a Fluent Builder Pattern with the following design principles:
WithBuilder() on RestRequestCookieValue, CookieValueComparer, and polymorphic FileAttachment classesIRequestBuilder to enable method chainingRequestBuilder is sealed to prevent subclass override and maintain invariantsCreate() is called, enabling safe repeated callsStringComparison.InvariantCultureIgnoreCaseRestSharp.RequestBuilder/
├── src/RestSharp.RequestBuilder/
│ ├── RequestBuilder.cs # Core builder class (743 lines)
│ ├── Extensions/RestRequestExtensions.cs # Entry points
│ ├── Interfaces/IRequestBuilder.cs # Public contract (338 lines)
│ └── Models/
│ ├── CookieValue.cs # Immutable cookie POCO
│ ├── CookieValueComparer.cs # Case-insensitive equality
│ └── FileAttachment.cs # Polymorphic file abstraction
├── tests/RestSharp.RequestBuilder.UnitTests/
│ ├── RequestBuilderTests.cs # 100+ test cases
│ └── RestSharp.RequestBuilder.UnitTests.csproj
├── .github/
│ ├── instructions/ # Comprehensive documentation
│ ├── copilot-instructions.md # AI development guide
│ └── workflows/ # CI/CD pipeline definitions
├── RestSharp.RequestBuilder.sln # Solution root
├── Directory.Build.props # Shared build properties
├── Directory.Packages.props # Centralized package versions
└── global.json # .NET SDK version pinning
dotnet --version)# Clone the repository
git clone https://github.com/brandonhenricks/RestSharp.RequestBuilder.git
cd RestSharp.RequestBuilder
# Restore packages
dotnet restore
# Build the solution
dotnet build RestSharp.RequestBuilder.sln -c Release
# Run tests
dotnet test RestSharp.RequestBuilder.sln -c Release
# Package locally (optional)
dotnet pack src/RestSharp.RequestBuilder/ -c Release -o ./artifacts
CookieContainerThe project adheres to strict coding standards:
The project includes 100+ MSTest unit tests covering:
CookieContainerRun tests with:
dotnet test RestSharp.RequestBuilder.sln -c Release
Contributions are welcome! Please follow these guidelines:
git checkout -b feature/your-feature-namedotnet build and dotnet test must passdotnet build RestSharp.RequestBuilder.sln passesdotnet test RestSharp.RequestBuilder.sln passes all testsFor deeper information, see the .github/instructions directory:
See also AGENTS.md for agent-specific development context and copilot-instructions.md for architectural deep dives.
RestSharp.RequestBuilder is licensed under the MIT license.