GithubHelp home page GithubHelp logo

dalsoft / dalsoft.restclient Goto Github PK

View Code? Open in Web Editor NEW
218.0 15.0 44.0 767 KB

The C# REST Client - the only REST/ HTTP Client you will ever need

Home Page: https://restclient.dalsoft.io

License: MIT License

C# 100.00%
restclient dynamic json c-sharp ihttpclientfactory csharp dalsoft rest-client dotnetcore

dalsoft.restclient's Introduction

DalSoft .NET REST Client for all platforms

If you find this repo / package useful all I ask is you please star it.

Nuget Help and chat on Gitter StackOverflow Docs

For everything you need to know, please head over to https://restclient.dalsoft.io

alt text

Just some of the things you can do with DalSoft.RestClient

Supported Platforms

RestClient targets .NET Standard 2.0 therefore supports Windows, Linux, Mac and Xamarin (iOS, Android and UWP).

.NET 5.0 and .NET 6.0 supported All versions of .NET Core supported All versions of legacy .NET Framework > 4.6.1 supported

Getting Started

Install via .NET CLI

> dotnet add package DalSoft.RestClient

Install via NuGet

PM> Install-Package DalSoft.RestClient

Example calling a REST API

You start by new'ing up the RestClient and passing in the base uri for your RESTful API.

For example if your wanted to perform a GET on https://jsonplaceholder.typicode.com/users/1 you would do the following:

Static Typed Rest Client

For the Static typed Rest Client just pass a string representing the resource you want access to the Resource method, and then call the HTTP method you want to use.

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

User user = await client.Resource("users/1").Get();
   
Console.WriteLine(user.Name);

Dynamicaly Typed Rest Client

For the Dynamicaly typed Rest Client chain members that would make up the resource you want to access - ending with the HTTP method you want to use.

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

var user = await client.Users(1).Get();
   
Console.WriteLine(user.name);

Note all HTTP methods are async

Recent Releases

About

RestClient is a very lightweight wrapper around System.Net.HttpClient that uses the dynamic features of .NET 4 to provide a fluent way of accessing RESTFul API's, making it trivial to create REST requests using a lot less code.

Originally created to remove the boilerplate code involved in making REST requests using code that is testable. I know there are a couple of REST clients out there but I wanted the syntax to look a particular way with minimal fuss.

RestClient is biased towards posting and returning JSON - if you don't provide Accept and Content-Type headers then they are set to application/json by default See Working with non JSON content.

Standing on the Shoulders of Giants

DalSoft.RestClient is built using the following great open source projects:

DalSoft.RestClient is inspired by and gives credit to:

dalsoft.restclient's People

Contributors

dalsoft avatar joakimjm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dalsoft.restclient's Issues

Add HttpHandler to RestClient constructor for authentication purposes

Currently without implementing IHttpClientHandler users are unable to provide authentication information outside of HTTP headers. This is limiting in cases where there is need to authenticate with NLTM or Kerberos.

In an answer to a question I had on Stack Overflow Darran said:

if you need this functionality I'll look at adding it to the ctor It would look like this:

HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential();
new RestClient("http://localhost/", handler);

Sine I definitely have this need and would prefer to not have to consistently create implementations of IHttpClientHandler I'd love to see this added to DalSoft.RestClient.

Issue with json im retrieving

I am having a issue and perhaps I am doing something wrong.
I am doing below (simpliefied for argument sake)
list result = await client.api.get()

it throws an error saying it cannot convert json array etc.

when I do var result = await client.api.get()
and when i copy the value from result it seems to have an extra { and } at beginning and end which aren't valid json when pasted into jsonlint.com. If i remember the extra { and } it parses the JSON correctly.

When i tried retrieving the same json using webclient , the data it retrieves doesnt have these extra braces.

Add Pipeline using syntactic sugar

It would be good to be able to do

new Config()
.Pipeline
.UseNoDefaultHandler()
.UseHandler((request, token, next) => next())
.UseRetryHandler)
.UseUnitTestHandler((request, token, next) => next());
.UseHttpClientHandler(config => config.Cookies = )

Timeout (and maybe DefaultHeaders) are not Thread Safe

HttpClient Timeout is not safe and has this check

I will be making changes so that Timeout will only be set once per instance via the constructor only.

My fear is that the same problem exists with DefaultHeaders which is a harder problem to solve, I will confirm this shortly.

The dynamic returned is immutable is this desirable?

Because you can't do this extension

            public static Task<T> Act<T>(this Task<dynamic> request, Action<T> act) where T : class
            {
                // Dynamic object is immutable see bug

                return request.ContinueWith(task =>
                {
                    act = act ?? (obj => { });
                    var response = (T)task.Result;
                    act(response);
                    return response;
                });
            }

RetryHandler to Support Func

Allow turning off default and provider on status code and exceptions, through use of a func.

Update documentation on what we consider a Transient failure

Proxy support

Hi, i'm looking for a way to use proxies (http/socks/chains)
Is that possible ?

WebRequestHandler in Pipeline

WebRequestHandler is .NET 4.5 only

Add test for WebRequestHandler.

Like HttpClientHandler WebRequestHandler should only be added to the Pipleline once.

URL Generated Has Trailing Slash

Hey @DalSoft,

Finally got the chance to hack on this and bumped into this problem.

I'm hacking on something that's using the PushBullet API - specifically (to get started) this resource.

I fired off a request like so:

Failing Code

dynamic client = CreateClient();
Me result = await client.Users.Me.Get();
return result;

This blew up hard, due to Implicit casting failing - but when I checked Fiddler, I noticed that I'd got a 404 back from the server.

Failing Request

GET https://api.pushbullet.com/v2/users/me/ HTTP/1.1
Authorization: Bearer {token}
Host: api.pushbullet.com
Connection: Keep-Alive

Failing Response

HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
Date: Sat, 31 Jan 2015 13:12:35 GMT
Server: Google Frontend
Cache-Control: private
Content-Length: 100

{"error": {"type":"invalid_request","message":"The resource could not be found.","cat":"~(=^โ€ฅ^)"}}

(lulz at the cat} ๐Ÿ˜€

I then hacked the request to remove the trailing slash and all was fine.

Successful Request

GET https://api.pushbullet.com/v2/users/me HTTP/1.1
Authorization: Bearer {token}
Host: api.pushbullet.com
Connection: Keep-Alive

There's still huge debate about whether or not trailing slashes should or shouldn't be there. I personally err on the side of:

"fuck it, if there isn't one we definitely know what resource they're trying to access."

What do you think? I had a quick look through the code and it seems this code is what needs to be looked at?

Happy to open a PR if wanted ๐Ÿ˜„

RestClientResponseObject

Hi,

In RestClientResponseObject.TryGetMember method the order is incorrect:

First should be->
if (binder.Name == "HttpResponseMessage") {
result = _httpResponseMessage;
return true;
}
Then the rest of the code, because I have a different response message depending on the HttpResponseMessage.StatusCode.

Thanks

Support complex objects in the QueryString

for example

unencoded
?PropertyName[index].ChildPropertyName[index].GrandchildPropertyName=test

encoded
?PropertyName%5Bindex%5D.ChildPropertyName%5Bindex%5D.GrandchildPropertyName=text

custom routes?

hi all

thank you for your library. i would love to learn more about it.

Is it possible to create custom routes for just one operation:

i.e. i need something like this:

clients/find_by_name/:name

where :name is essentially :id - i'll be using that parameter to search for a client with a matching name - and if i should so find one, then a json object representing that client will be returned.

right now i'll just have to create three different new rest clients with different urls. not sure if that's the way to go though.

rgds

Ben

Allow strings in mutable verbs

Added the functionality - for edge cases, but JSON strings will not be validated, and will be passed as is. This functionality is useful if the resource server needs something that is not standard or invalid like a signed JWT or something.

Json will always be validated if you use objects, and this should be your preference, even if you need to write a custom handler to support what you need. A custom handler is still safer than just posting an unchecked string.

baseUri

BaseUri should validate that it is a non empty valid Uri

Simple array nested in a complex array doesn't work as expected

Currently the SimpleArray properties such as Length etc are added to the QueryString instead of the Array's values.

await Test.Query.Get(new
{
   nestedArray = new[] 
   {
      new
      {
            simpleProp = "simple prop",
            simpleArray = new[] { "simple 0", "simple 1" }
      }
   }
});

Attach files to a request

Is it possible to attach a file for Post() ?

You can set the Content-Type: multipart/form-data.

If yes ? Do you have an example ?

Move type checking to DefaultJsonHandler

Move the type checking to DefaultJsonHandler as some handlers may want to have a string or primitive and as it stands this would throw

if (!args[0].GetType().GetTypeInfo().IsClass || args[0] is string) throw new ArgumentException("Please provide a class to be serialized to the request body for example new { hello = \"world\" }");

The equivalent VB.net code of the example?

This exmple:

dynamic client = new RestClient("http://jsonplaceholder.typicode.com");
await client.Users(1).Get();

What I try:

Dim client As Object = New RestClient("http://jsonplaceholder.typicode.com")
Await client.Users(1).Get()

Get this error:
System.InvalidCastException: 'Conversion from type 'MemberAccessWrapper' to type 'Boolean' is not valid.'

Not sure how to do a query string

I've looked at the query string examples but not sure how to do what I want
I basically need to pass 3 queries from date, todate and api_key which looks like below.
http://apiurl/pay-runs?fromDate=date&toDate=date&api_key=apikey

i tried addint this to where the queries stoart .Query(new { api_key = apikey }).Query(new { fromDate = dfrom }).Query(new { toDate = dto }).get()

but it doesnt seem to work.
what is the correct way for this scenario?

Fluent Headers

It would be nice to be able to do this:

dynamic` client = new RestClient();

client
    .Headers(new { ContentType = "text/html" })
    .Api
    .Person(1)
    .Post(new { ... })

Headers should support an object as well as a Dictionary<string, string>

Once this is implemented I will be making the DefaultHeaders readonly

IPv6 network problem

i can connect to web servis wtih iphone in ipv4 network but cant connect with iphone in ipv6 network

Rest service user and password login

Hi, how can i set user and password to login rest service on DalSoft.RestClient, read wiki but couldnt found any information about that

Edit: i found in closed issues, thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.