Skip to content

Instantly share code, notes, and snippets.

@steveevers
Created August 23, 2018 05:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steveevers/618142fd7a9d235a66c71c3610ffb206 to your computer and use it in GitHub Desktop.
Save steveevers/618142fd7a9d235a66c71c3610ffb206 to your computer and use it in GitHub Desktop.
A class used to construct REST requests.
using System;
using RestSharp;
namespace Application.Services
{
public class RequestBuilder
{
private IRestRequest request;
#region Static Constructors
public static RequestBuilder GET(string resourceUri)
{
return Init(resourceUri, Method.GET);
}
public static RequestBuilder POST(string resourceUri)
{
return Init(resourceUri, Method.POST);
}
public static RequestBuilder PUT(string resourceUri)
{
return Init(resourceUri, Method.PUT);
}
public static RequestBuilder DELETE(string resourceUri)
{
return Init(resourceUri, Method.DELETE);
}
#endregion
public RequestBuilder WithBody(string body)
{
if (this.request.Method == Method.POST || this.request.Method == Method.PUT || this.request.Method == Method.DELETE)
{
this.request.AddJsonBody(body);
}
return this;
}
public RequestBuilder WithBody(object body)
{
this.request.AddJsonBody(body);
return this;
}
public RequestBuilder WithFile(string key, byte[] data, string name)
{
this.request.AddFile(key, data, name);
return this;
}
public RequestBuilder WithHeader(string key, string value)
{
if (!string.IsNullOrEmpty(value))
{
this.request.AddHeader(key, value);
}
return this;
}
public RequestBuilder WithParameter(string key, string value)
{
this.request.AddParameter(key, value);
return this;
}
public RequestBuilder WithParameter(string key, dynamic value)
{
string s = value.ToString();
this.request.AddParameter(key, s);
return this;
}
public RequestBuilder WithQueryStringParameter(string key, string value)
{
this.request.AddQueryParameter(key, value);
return this;
}
public RequestBuilder WithUrlSegment(string key, string value)
{
this.request.AddUrlSegment(key, value);
return this;
}
public RequestBuilder WithUrlSegment(string key, dynamic value)
{
string s = value.ToString();
this.request.AddUrlSegment(key, s);
return this;
}
public IRestRequest Build()
{
return this.request;
}
private static RequestBuilder Init(string resourceUri, Method method)
{
var resource = resourceUri.StartsWith("/", StringComparison.CurrentCultureIgnoreCase) ? resourceUri.Substring(1) : resourceUri;
var builder = new RequestBuilder { request = new RestRequest($"api/{resource}", method) };
builder.request.AddHeader(C.Headers.Accept, C.Headers.Json);
return builder;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment