How to Access Resources

The URL builder works by simply chaining members that would make up the resource you want to access - ending with the HTTP method you want to use.

Accessing a resource by identity

Accessing a resource by identity works as you would expect for example if your wanted to perform a GET on https://jsonplaceholder.typicode.com/users/1 you would do the following:

dynamic client = new RestClient("https://jsonplaceholder.typicode.com");

await client.Users(1).Get();

If the resource is annoyingly case sensitive for exampe if the API responded to only /users not /Users your call would be await client.users(1).Get();

For GET, HEAD, DELETE you can also pass the resource identity in the method, for example if your wanted to perform a DELETE on https://jsonplaceholder.typicode.com/users/1:

dynamic client = new RestClient("https://jsonplaceholder.typicode.com");

await client.Users.Delete(1);

The resource identity can be any primitive type

Nested resources

Nested resources again work as you would expect for example if your wanted to perform a GET on https://jsonplaceholder.typicode.com/users/2/comments you would do the following:

dynamic client = new RestClient("https://jsonplaceholder.typicode.com");

await client.Users(2).Comments.Get()

Awkward resources

You will come across an API that has a resource that isn’t valid C# syntax. To escape invalid C# syntax in a resource use the Resource method for example:

dynamic client = new RestClient("https://jsonplaceholder.typicode.com");

await client.Users(2).Resource("awkward-resource-with-dashes").Get()

Vanity API - Formatting the Resource URL

Sometimes the way you want to access the API in C#, and what the server will respond to are in conflict.

Lets say you wanted to access https://case-sensitive-api.com/users/1 the server is case sensitive, but you wanted to access like so:

dynamic client = new RestClient("https://case-sensitive-api.com");

var result = await client.Users(1).Get()

It won’t work by default as the server expects you to access the resource using lower case i.e. await client.users(1).Get().

However it is trivial to format the URL generated using DalSoft.RestClient using Handlers.

dynamic client = new RestClient("https://case-sensitive-api.com", new Config()
	.UseHandler(async (request, token, next) =>
	{
		request.RequestUri = new Uri(request.RequestUri.ToLower()); // Deal with case sensitive resources;
		return await next(request, token); //Call next handler in pipeline
	}));

var result = await client.Users(1).Get()	

You can use this technique to easily create SDK’s that make sense for your domain.