Git Product home page Git Product logo

reactiveui / refit Goto Github PK

View Code? Open in Web Editor NEW
8.1K 176.0 721.0 15.09 MB

The automatic type-safe REST library for .NET Core, Xamarin and .NET. Heavily inspired by Square's Retrofit library, Refit turns your REST API into a live interface.

Home Page: https://reactiveui.github.io/refit/

License: MIT License

C# 97.97% CSS 1.54% Batchfile 0.43% Dockerfile 0.06% Shell 0.01%
dotnet dotnet-core http xamarin c-sharp json xml

refit's Introduction

Build Code Coverage #yourfirstpr



What is ReactiveUI?

ReactiveUI is a composable, cross-platform model-view-viewmodel framework for all .NET platforms that is inspired by functional reactive programming, which is a paradigm that allows you to abstract mutable state away from your user interfaces and express the idea around a feature in one readable place and improve the testability of your application.

πŸ”¨ Get Started πŸ› Install Packages 🎞 Watch Videos πŸŽ“ View Samples 🎀 Discuss ReactiveUI

Book

There has been an excellent book written by our Alumni maintainer Kent Boogart.

NuGet Packages

Install the following packages to start building your own ReactiveUI app. Note: some of the platform-specific packages are required. This means your app won't perform as expected until you install the packages properly. See the Installation docs page for more info.

Platform ReactiveUI Package NuGet
.NET Standard ReactiveUI CoreBadge
ReactiveUI.Fody FodyBadge
Unit Testing ReactiveUI.Testing TestBadge
WPF ReactiveUI.WPF WpfBadge
UWP ReactiveUI.Uwp UwpBadge
WinUI ReactiveUI.WinUI WinUiBadge
MAUI ReactiveUI.Maui MauiBadge
Windows Forms ReactiveUI.WinForms WinBadge
Xamarin.Forms ReactiveUI.XamForms XamBadge
Xamarin.Essentials ReactiveUI CoreBadge
AndroidX (Xamarin) ReactiveUI.AndroidX DroXBadge
Xamarin.Android ReactiveUI.AndroidSupport DroBadge
Xamarin.iOS ReactiveUI CoreBadge
Xamarin.Mac ReactiveUI CoreBadge
Tizen ReactiveUI CoreBadge
Blazor ReactiveUI.Blazor BlazBadge
Platform Uno ReactiveUI.Uno UnoBadge
Platform Uno ReactiveUI.Uno.WinUI UnoWinUiBadge
Avalonia Avalonia.ReactiveUI AvaBadge
Any ReactiveUI.Validation ValBadge

Sponsorship

The core team members, ReactiveUI contributors and contributors in the ecosystem do this open-source work in their free time. If you use ReactiveUI, a serious task, and you'd like us to invest more time on it, please donate. This project increases your income/productivity too. It makes development and applications faster and it reduces the required bandwidth.

Become a sponsor.

This is how we use the donations:

  • Allow the core team to work on ReactiveUI
  • Thank contributors if they invested a large amount of time in contributing
  • Support projects in the ecosystem

Support

If you have a question, please see if any discussions in our GitHub issues or Stack Overflow have already answered it.

If you want to discuss something or just need help, here is our Slack room, where there are always individuals looking to help out!

Please do not open GitHub issues for support requests.

Contribute

ReactiveUI is developed under an OSI-approved open source license, making it freely usable and distributable, even for commercial use.

If you want to submit pull requests please first open a GitHub issue to discuss. We are first time PR contributors friendly.

See Contribution Guidelines for further information how to contribute changes.

Core Team


Glenn Watson

Melbourne, Australia


Rodney Littles II

Texas, USA


Artyom Gorchakov

Moscow, Russia


Colt Bauman

South Korea


Chris Pulman

United Kingdom

Alumni Core Team

The following have been core team members in the past.


Geoffrey Huntley

Sydney, Australia


Kent Boogaart

Brisbane, Australia


Olly Levett

London, United Kingdom


AnaΓ―s Betts

San Francisco, USA


Brendan Forster

Melbourne, Australia


Claire Novotny

New York, USA

.NET Foundation

ReactiveUI is part of the .NET Foundation. Other projects that are associated with the foundation include the Microsoft .NET Compiler Platform ("Roslyn") as well as the Microsoft ASP.NET family of projects, Microsoft .NET Core & Xamarin Forms.

refit's People

Contributors

alexandru-calinoiu avatar anaisbetts avatar bennor avatar carl-berg avatar clairernovotny avatar dahlbyk avatar danlyons-softek avatar dashell-james avatar dependabot-preview[bot] avatar dependabot[bot] avatar drakelambert avatar dreamescaper avatar farcasclaudiu avatar flagbug avatar ghuntley avatar glennawatson avatar james-s-tayler avatar jamiehowarth0 avatar mariusvolkhart avatar mburbea avatar ncruces avatar nekresh avatar panetta-net-au avatar renovate[bot] avatar sergio0694 avatar sharwell avatar stevewgh avatar styxxy avatar timothymakkison avatar yuri-voloshyn 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  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

refit's Issues

PCL Support

Hi Paul,

Any thoughts on the PCL support?

The latest Nuget fails under profile portable-net45+win+wp80 due to Castle.Core dependency.

JsonConverters not being used?

I'm not sure if I missed something obvious, but I'm not seeing my DateTime JsonConverter being used in outbound parameters.

While poking at an API that expects dates like this: "yyyy-MM-dd HH:mm:ss" (e.g., "2014-11-07 16:32:54", or "2014-11-07+16%3A32%3A54" in querystring), I kept getting errors about invalid date format. It looks like the JsonConverter I am trying to apply isn't actually getting used. Instead, my DateTimes look like this: "11/7/2014+4:32:54+PM".

screen shot 2014-11-12 at 15 26 49

I was seeing this running against both v2.0.2 via NuGet and a version built from master grabbed yesterday evening (Nov. 11 MDT).

Approach 1

I tried the Json.NET defaults approach:

JsonConvert.DefaultSettings = 
    () => new JsonSerializerSettings () { 
        Converters = { new SomeDateTimeConverter () },
    };

Just to confirm the converter itself works, I gave it a [successful] run right after that.

var testDate = new DateTime (2014, 11, 7, 16, 32, 54);
string testDateJson = JsonConvert.SerializeObject (testDate);
System.Diagnostics.Debug.Assert (testDateJson == "2014-11-07 16:32:54"); // success

Approach 2

I also tried adding the converter to the parameter. Totally a shot in the dark, though, since I wasn't even sure that was supposed to be a supported approach.

[Get ("/test/something1/")]
Task<SomeResult> GetResult ([JsonConverter (typeof(SomeDateTimeConverter))]DateTime someDate);

Repro Code

All the relevant code mentioned here is pulled from a repro project I put together and stuck in a Gist.

Repro steps:

  1. New Xamarin.Android project
  2. Add Refit via NuGet (v2.0.2)
  3. Add Microsoft.Net.Http via NuGet to get it to build.
  4. Replace content of MainActivity.cs with Gist code.
  5. Insert your own Runscope debug bucket ID in the RestService.For... call.
  6. Run on device; click the big ol' button to send off requests.
  7. Check resulting outbound URLs in Runscope and see DateTimes in this form: "11/7/2014+4:32:54+PM" (URL decoded from "11%2f7%2f2014+4%3a32%3a54+PM")

Works on Mono?

I'm wondering whether Refit works on Mono on Linux? The readme mentions Xamarin.Mac but I don't know whether this is the same as the open-source Mono.

Overloaded method support

As of now, refit doesn't handle method overload.
The methods dictionary can't be built because of DuplicateKeyException.

Would it be interesting to support WebApi's style method overload ?

IEnumerable<X> Get();
X Get(int id);

json.net dependency and refit dependency

This is my 'Client' project

public interface IClientApi {
    [Get("/")]
    Task<string> Home();

    [Get("/{id}")]
    Task<string> GetById(int id);
}

public class ClientApi : IClientApi {
    private IClientApi _client;

    public ClientApi() {
        var c = new HttpClient {BaseAddress = new Uri("http://localhost:7820")};
        _client = RestService.For<IClientApi>(c);
    }

    public async Task<string> Home() {
        return await _client.Home();
    }

    public async Task<string> GetById(int id) {
        return await _client.GetById(id);
    }
}

This is my 'Consumer' project:

private static void Main(string[] args) {
    var client = new ClientApi();
    Console.WriteLine(client.Home().Result);
    Console.WriteLine(client.GetById(1).Result);
}

Why i have to install json.net and refit in my consumer project? And why isn't json.net a dependency of refit nuget package?

REST attributes don't handle non-lowercase substitutions

If we have a service like:

 public interface IEmployeeApi
 {        
    [Get("/api/v2/employee/{employeeId}")]
    Task<Employee> Get(int employeeId)
}

If i call ,for example, employeeApi.Get(1) refit will attempt to make a request to /api/v2/employee/{employeeId} instead of /api/v2/employee/1

If I change the string in the Get attribute to "/api/v2/employee/{employeeid}" , it works fine.

InterfaceStubGenerator not working on build

I'm getting the following error on my build:

C:\Program Files (x86)\MSBuild\12.0\bin\amd64\Microsoft.Common.CurrentVersion.targets(1069, 5): error MSB3073: The command ""..\packages\refit.2.1.0\tools\InterfaceStubGenerator.exe" "C:\TeamCity\buildAgent\work\5c154ea65fba2a12\src\Website\RefitStubs.cs" "App_Start\IoC.cs;App_Start\LessTransform.cs;App_Start\RouteConfig.cs;App_Start\BundleConfig.cs;Classes\BundleHelper.cs;Classes\FormHelper.cs;Controllers\CallbackController.cs;Controllers\T101AsyncController.cs;Models\ConfirmationViewModel.cs;Orchestrators\ISecurePaymentOrchestrator.cs;Controllers\SecureController.cs;Orchestrators\SecurePaymentOrchestrator.cs;Controllers\T101Controller.cs;Global.asax.cs;Models\PaymentViewModel.cs;Properties\AssemblyInfo.cs"" exited with code 3.

I don't have any refit stub classes in that project (they're all in a different one that is referenced in this one) so I'm not sure why the generator is trying to check all these.

Or am I wrong in what this .exe is trying to achieve?

Should specify that I'm using teamcity for build.

Conflicting types in RefitStubs.cs

I have two different sets of REST API in my project, both enabled by Refit. Both API reference a type named Project, but these are separate and unrelated Project classes that live in different namespaces. Unfortunately, when Refit puts stubs for both API into the same file, with one set of usings, I get a naming conflict.

One way to resolve this (short of me renaming my classes, which may not always be possible) is to have the InterfaceStubGenerator.cs generate fully qualified type names rather than reuse the names it finds in the interface file. To do that, the Roslyn syntax model needs to be converted to a semantic model and queried.

Possibly useful reading:
http://stackoverflow.com/a/9336238/56499
http://blogs.msdn.com/b/csharpfaq/archive/2011/11/23/using-the-roslyn-symbol-api.aspx

error with return type of Task (no generics)

Repro: http://1drv.ms/1itgwUu

Hi, I'm trying to do a simple test with refit like this:

public interface IClientApi {
    [Post("/")]
    Task PostHome();
}

When i call RestService.For<IClientApi>("http://localhost:7820"); i have the following error:

An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
Additional information: This operation is only valid on generic types.

   at System.RuntimeType.GetGenericTypeDefinition()
   at Refit.RestMethodInfo.determineReturnTypeInfo(MethodInfo methodInfo) in c:\Users\Paul\github\refit\Refit\RequestBuilderImplementation.cs:line 412
   at Refit.RestMethodInfo..ctor(Type targetInterface, MethodInfo methodInfo) in c:\Users\Paul\github\refit\Refit\RequestBuilderImplementation.cs:line 321
   at Refit.RequestBuilderImplementation.<>c__DisplayClass8.<.ctor>b__0(MethodInfo x) in c:\Users\Paul\github\refit\Refit\RequestBuilderImplementation.cs:line 42
   at System.Linq.Enumerable.<SelectManyIterator>d__14`2.MoveNext()
   at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
   at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector)
   at Refit.RequestBuilderImplementation..ctor(Type targetInterface) in c:\Users\Paul\github\refit\Refit\RequestBuilderImplementation.cs:line 36
   at Refit.RequestBuilderFactory.Create(Type interfaceType) in c:\Users\Paul\github\refit\Refit\RequestBuilderImplementation.cs:line 20
   at Refit.RequestBuilder.ForType(Type interfaceType) in c:\Users\Paul\github\refit\Refit\RequestBuilder.cs:line 37
   at Refit.RequestBuilder.ForType[T]() in c:\Users\Paul\github\refit\Refit\RequestBuilder.cs:line 42
   at Refit.CastleRestService.For[T](HttpClient client) in c:\Users\Paul\github\refit\Refit\CastleRestService.cs:line 16
   at Refit.RestService.For[T](HttpClient client) in c:\Users\Paul\github\refit\Refit\RestService.cs:line 34
   at Refit.RestService.For[T](String hostUrl) in c:\Users\Paul\github\refit\Refit\RestService.cs:line 40
   at TesteClient.Client.ClientApi..ctor() in c:\Users\deschamps\Documents\Visual Studio 2013\Projects\TesteClient\TesteClient.Client\ClientApi.cs:line 9
   at TesteClient.Consumidor.Program.Main(String[] args) in c:\Users\deschamps\Documents\Visual Studio 2013\Projects\TesteClient\TesteClient.Consumidor\Program.cs:line 7
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Support Web API routing attributes

It would be nice if refit supported Web API attributes (coming in the next version of Web API) so the same routing can be shared on the server and client.

I think the best way to implement this would be to support overriding the underlying model directly (e.g. like IContractResolver in Json.NET) and then having a seperate Refit.WebApi package.

Support returning IQueryable to save much boilerplate

I heart refit. And with IQueryable it'd be πŸ‘! Would you accept a PR that accomplishes this?

(1) Get pagination (and sorting) for free! This is important since any good API will force pagination on almost every returned array.

// Instead of:
var users = await api.SearchUsers("Joe", startIndex: 0, maxResults: 25).ToList();

// Do this:
var users = await api.SearchUsers("Joe").Skip(0).Take(25);

(2) Allow flexible filtering, reducing the number of obscure interface methods.

// Instead of:
IList<User> GetUsersWithNameSinceLogInTime(string name, DateTime time);

// Do this:
var users = 
    from u in api.GetUsers()
    where u.FirstName == "Joe" && u.LastLoggedIn < time
    orderby u.LastLoggedIn
    select u;

These can be accomplished by simply returning Task<IQueryable<T>> from the interface method.

public interface INeatoApi
{
    [Get("/users")]
    Task<IQueryable<User>> GetUsers();
}

Under the hood refit would need to generate rest-like query string params for the extra LINQ goodies. The OData spec would be great for this. In fact, OData brings more than just paging and filtering. There are expand/include and projection potentials too. Even other fun goodies like api.GetUsers().AsAutomaticPaging() which will lazy-fetch the next 25 as you foreach through the Enumerable.

refit does not handle JSON return types with variable members

So this is something I've been tracking and trying to figure out in my fork, but I haven't come up with a good solution yet. It's not really a bug in refit, but it's more about the problem with serializing JSON to C# in general.

I'm calling an API using refit that returns a JSON object with a list of properties. The problem is the properties can vary.

{
  "timestamp": 1398877243,
  "base": "USD",
  "rates": {
    "AED": 3.672913,
    "AFN": 56.866025,
    "ALL": 101.06385,
    "AMD": 415.960999,
    /* 165 currencies */
    "YER": 215.036499,
    "ZAR": 10.54031,
    "ZMK": 5253.075255,
    "ZMW": 6.312353,
    "ZWL": 322.355006
  }
}

So, we could hard code a type that contains all 175 currencies, but the currency list could change in the future. Ideally, the API would return the currency list as an array of ISO code: rate object

"rates" : [
{"code": "AED", "rate":"3.6"}
]

So what I'm looking for is a way to tell refit to serialize the "rates" object as a hashtable or List OR a way to create the "rates" member of the C# object as an expando object.

So the question is: Is this something to be solved in refit or in JSON.net?

OAuth2 flow

Hi,

Do you have a suggestion for a best practice on implementing the OAuth2 authorization flow, especially the refresh token usage.

It will need to do something like:

original request -> repond: 401 -> request refresh_token -> respond: 200 -> original request -> respond: 200

Thank you,

Stubs aren't generated unless service is instantiated in the same project

InterfaceStubGenerator needs there to be a call to RestService.For<ISomeApi>() in the same project that ISomeApi is defined or it won't generate a stub for it.

We should be able to fix this by looking for all interfaces that have an attribute derived from HttpMethodAttribute on a method and making stubs for them.

This awesome error shows up when you try to create the service later too: https://gist.github.com/screamish/ccc46cb849cc4497ea8e

Dealing with non-Refit methods declared on a Refit interface

At the moment methods that are defined on a Refit interface but don't have Refit attributes are stubbed to throw an exception.

Feel free do close this if you think it's A Dumb Idea, but what might be cool is allowing for (or requiring :trollface:) the methods to be implemented manually -- effectively replacing what we're currently using extension methods to implement.

There are two options here:

  1. Just don't implement them at all, requiring people to create a partial class and implement the methods before their project will compile.
  2. Keep the existing virtual method which throws an exception, and rewire RestService.For() to look for any derived classes in the same assembly, allowing people to derive from AutoGeneratedIXXX to override these methods.

Keen to hear your thoughts.

Using Refit with a cross platform library.

I am putting together a PCL that is, essentially, a client for a rest based service. When its working I want to push it to github and into nuget...

So rather than code all the usual stuff by hand I thought I'd give Refit a try.

My question is: what is the best way to put together the client? I started with a PCL targeting the usual suspects (WinPhone, Xamarin Android, etc) but Refit has platform specific assemblies.

I assume that I would need to follow Refit's pattern and have a platform specific project even if all I do is include the same source files (and platform specific Refit?)...

Any advice very much appreciated πŸ˜„

Package as Xamarin Studio component

It would be nice to have this library packaged as Xamarin Studio component and make easy to add Refit in any Xamarin.Android or Xamarin.iOS projects.

Support for getting response headers

(This issue is at the request of @paulcbetts over twitter, in which I stated I'm willing to give a pull req a try, but some discussion on scenarios first.)

I would like to see support for getting response headers out of the remote api call while still using a strongly typed response (or none at all). This would be for making calls against APIs (ex the azure management api) that return a unique request-id as a response header, which can be used in support cases when something unexpected/bad happens, or more frequently in the case of asynchronous calls in which a call is made against the api such as swapping an azure deployment, in order to take that returned request-id and query its status in a future api call.

Given the way refit is exposed to it's user, the most natural way I feel would be to use attributes i.e.

// async api that returns no body
[Post("/some/asyncapi/{someId}")]
Task SomeAsyncRemoteApiCall(int someId, [ResponseHeader("x-request-id")] out string requestId);

// async api that returns body and requestid header
[Post("/some/asyncapi/{someId}")]
Task<SomeResponse> SomeAsyncRemoteApiCall(int someId, [ResponseHeader("x-request-id")] out string requestId);

I suppose that an alternative to the first one could be

[Post("/some/asyncapi/{someId}")]
[return: ResponseHeader("x-request-id")]
Task<string> SomeAsyncRemoteApiCall(int someId);

where the returned Task is for the header, not the string content because the request doesn't return a body. But that seems a little wonky IMO.

Thoughts/comments/insults?

Customize url/querystring serialization

Hi,

I have an issue where a web UI project runs different UI cultures for different users. This has a side effect of for example DateTime being serialized differently depending on the culture. What i would like is to customize how refit serializes objects into the url/querystring. Is there any possible extension points for that, or could there be? If so, I'd be happy to provide a PR with a suggestion.

plug different JsonSerializer or different SerializationSettings

is this possible? From what i saw: no, but i could be wrong.

Do you guys think its worth doing?

We're using refit but we have to serialize stuff with TypeNameHandling.All.

Currently, we're sending just strings and serializing before sending the request
If you guys this is something worth doing, i can try to implement it :)

Lists as url parameters

I'm not sure if Refit supports list arguments in the url. As of now i have had to wrap lists in another type and serialize its values with comma separation. And then add some custom handling on the receiving side to turn it back into a list. I would however prefer it if a call like this:

public IMyApi
{
    [Get("api/resource")]
    Task<Response> GetResources(List<int> value);
}

var api = RestService.For<IMyApi>();
api.GetResource(new List<int>{ 1, 2, 3});

would generate a request like GET /api/resource?value=1&value=2&value=3

What do you guys think about that? Good idea or waste of time?

parsing url template placeholders bug.

Hi guys,
I've encountered a weird issue with the Url template fields matching.
I've a simple REST Interface with the following signature:

    [Delete("/api/attachment/{resourceType}/{resourceId}/{filename}")]
    Task DeleteAttachment([AliasAs("resourceId")] string resourceId, [AliasAs("filename")] string filename, [AliasAs("org")] string org, [AliasAs("resourceType")] string resourceType);

if when I make a call and inspect logs, it seems that the engine don't replace the resourceType and resourceId placeholders which isn't the case for other parameter alias names.
If I change them to id, type respectively, it works fine.

    [Delete("/api/attachment/{type}/{id}/{filename}")]

Just want to know if this is some kind of special case or a possible bug in the API.
Regards,
Oualid

Please provide support for WinRT and/or Xamarin.iOS

This library is brilliant, and to become more perfect than it already is, just need to provide support for WinRT and Xamarin.iOS platforms.

Please, could you help me? I need WinRT version of that library.

Thank you very much.

Stub implementations not created with pre-paren attribute whitespace

I haven't nailed down exactly what caused this (updating Refit to 2.1.0, updating Xamarin Studio, putting more air in my car's tires for cold weather, who knows?), but somewhere along the line the API in my Xamarin.Android app stopped getting a stubbed out version in RefitStubs.cs when I built the project. The symptom was triggering the well-worded exception from v2.1.0 telling me my interface didn't "look like a Refit interface". After lots of digging/reverting/cursing, here's the resulting difference.

Working

[Get("/users/{user}")]
Task<User> GetUser(string user);

Not so much with the working

[Get ("/users/{user}")]
Task<User> GetUser(string user);

In case you missed it, the only difference is the space between the Get and the open parenthesis
([Get ( vs. [Get().

Two methods

Oddly, if there are two methods, one with a space and one without the space (order doesn't matter), it generates the stub just fine. If all the methods have the space (tested to three), nothing is generated.

Setup (since this could be outside Refit's control)

  • OS X 10.10.1
  • Xamarin Studio 5.5.3
  • Xamarin.Android 4.18.1

InterfaceStubGenerator causes namespace clash

using My.Large.Namespace;
using OAuth = Thinktecture.IdentityModel.Client;

public interface IAccountClientApi
{
    [Get("/Account/UserInfo")]
    Task<UserInfoResponse> GetUserInfo([Header("Authorization")]string authorization);
}

Above testcode will cause a namespace clash in the RefitStubs.cs since the generator copies the namespaces like:

using My.Large.Namespace;
using Thinktecture.IdentityModel.Client;

which produces a collision on the type UserInfoResponse in the RefitStubs.cs

Releases

Hi,
I'm stuck with issue #21 that seems to have been fixed some time ago, yet the package up on nuget is older. Are there any plans to release a new version or should i just use a local reference in my case? I prefer not to use local references, but i don't really see a way out rather than pushing up a new package on private nuget feed, but that kinda takes me out of the loop for potential new releases. Any advice?

Capture redirects instead of throwing 404 or possibly more detail in the errors

This is more of an exploratory question than an "its broken" as I'm trying to get my head around what I might want to happen.

I'm using Refit to allow me to streamline testing an API we have and for the most part its great - but we have one method that returns a redirect (a choice of 3 with additional data depending) so of course the code attempts to follow the redirect and for my test I end up with a 404 and not a lot more information (at least not that I can see in the error analyser).

So... I'd either a) like to suppress the redirect or b) to have more information about the error (this morning I've managed lots of 400s, a few 500s and some 404s - some of which were failing to set the right URL and some of which were "no actually it worked but example.com/success doesn't exist).

Thoughts?

Revert to single solution now that PCL is OSS and RTM?

When I went down the path of adding Silverlight 5 support, my initial pull request was rejected as I implemented it as a PCL but took a dependency on some MS libraries that weren't OSS and multi-platform friendly at the time.

Given the recent liberalisation of licensing around PCL and HttpClient, etc, can a simplification of the project source code be achieved? (i.e. does there still need to be Refit-VisualStudio.sln, Refit-XamarinStudio.sln, + a number of platform-specific .csproj files?)

RefitInternalGenerated.PreserveAttribute.X is never assigned to, and will always have its default value false

Howdy guys, a discussion before the pull request.

It seems that any interface w/ Visual Studio upon compilation results in two CS0649 warnings. It's unclean and results in build failures if Visual Studio is configured to fail builds on warning (as it should be)

Example interface:

[Headers("User-Agent: " + AppSettings.ApiClientUserAgent)]
public interface IEndlessCatsApi
{
    /// <remarks>
    /// - You can redefine the user-agent header on a per request basis via: [Headers("User-Agent: ELinks/0.9.3 (textmode; Linux 2.6.11 i686; 79x24)"]
    /// - You can remove the user-agent header on a per request basis via: [Headers("User-Agent")]
    /// </remarks>
    [Get("/cats")]
    Task<List<Cat>> GetMoreCats([Header("X-Auth-Token")] string apiKey);
}

The offending fields:

Warning 1   Field 'RefitInternalGenerated.PreserveAttribute.AllMembers' is never
assigned to, and will always have its default value false

Warning 2   Field 'RefitInternalGenerated.PreserveAttribute.Conditional' is never
assigned to, and will always have its default value false

Possible solution is a PR that edits tools/GeneratedInterfaceStubTemplate.mustache as follows.

From:

    //
    // Field
    //
    public bool AllMembers;

    public bool Conditional;

To:

#pragma warning disable 0649
    //
    // Field
    //
    public bool AllMembers;

    public bool Conditional;
#pragma warning enable 0649

πŸ‘ or πŸ‘Ž or πŸ‘Š?

More convention: complex type should default to [Body]

Right now it seems like you need to put [Body] on a parameter you want to be in the body. How about reversing that or at least making the defaults based on the verb.

I.e., for PUT/POST, a complex type would go in the body and any other parameters to the query string.
for GET, a complex type would translate to a query string parameter along with any other parameters.

Silverlight support?

This library would nicely remove some code we have in our LOB Silverlight app. Is adding support for SL (at least 4, probably 5 would be ok) something that is on the radar, or probably pretty easy for someone to add and submit a pull request for?

Baseadress with subdirectory doesn't use the subdirectory when making requests

I have encountered a problem when base adress that is not the same as the domain:
For instance

    public interface IGitHubApi
    {
        [Get("/{username}")]
        Task<User> GetUser(string userName);
    }

    ....
    var fixture = RestService.For<IGitHubApi>("https://api.github.com/users/");
    var result = fixture.GetUser("octocat"); //will make a request for https://api.github.com/octocat, which is not what i want...

same applies if i create an HttpClient and set the base adress myself...

Provide a way to supply authentication attributes

A lot of REST API's require some form of authentication, be it via BASIC or OAuth (Bearer:) HTTP header or some other method.

It would be great if you could expose some way from the factory class to provide authentication credentials. Maybe, for example:

RestService.WithAuthentication.Basic("username","password")
                 .For<IGithubApi>();

and

RestService.WithAuthentication.OAuth2(accessToken, "Bearer") // second argument is header name, default it to Bearer
                 .For<IGithubApi>();

Multipart requests

Hey Paul,

I saw on the roadmap that there are plans to handle Multipart requests. What was your idea on how to implement it as I need it for file uploads and maybe I can help out with implementing it?

Alternatively would it make sense to allow passing in a parameter of HttpContent and in such a case assign it directly to the Content property of the HttpRequestMessage? This is sort of similar to how you handle Streams....? This will also allow for a lot of flexibility to allow users to structure the request exactly the way they want to.

Thanks

Usage of alternative (JSON / De-)Serializers

Good morning,

I just started playing with refit and I was wondering whether it was possible to use an alternative Json serializer and deserializer than Json.Net? As far as I can see it its hard-wired mostly in RequestBuilderImplementation.cs, but I've come to love Jil, been using NetJson in another project and some might use protobuf, MessagePack or some other formats.

While those might not provide support for the exact same amount of platforms as refit does, it might be nice to have a choice and I was wondering, whether the hard-coded usage of Json.net could be de-coupled and one could provide custom (de)serialization providers for refit?

Basically something like providing a Serializer registration point in https://github.com/paulcbetts/refit/blob/master/Refit/RefitSettings.cs, use that one instead of Json.Net directly?

I've forked away refit and started dabbling with this idea but wanted to check upfront whether this is something you might be ok with?

Cheers,
-J

Composing multiple interfaces for one API.

Hi,

Firstly, sorry if this is a obvious question, but is it possible to have one big interface/api defined in multiple pieces?

Maybe a folder structure like this? Where each interface is in its own folder inside a class.

/Acme
  AcmeApi.cs (IAcmeApi interface)
  /photos
    /IPhotosApi (acme.com/api/photos)
  /videos
   /IVideosApi (acme.com/api/videos)

then using just the IAcmeApi interface

var acmeApi = RestService.For<IAcmeApi>("https://api.acme.com");

var stuff = await acmeApi.DoStuff("banana");
// or maybe
var stuff = await acmeApi.Videos.DoStuff("banana");

I hope it makes sense.
Thank you.

Missing Dependency or problem in the nuget definition?

Not sure if it is something I am doing or something missing in the nuspec .

Create a console app (4.5.1 is fine or an iOS app if you prefer). Use nuget to add refit. Compile the app.

Error: The type or namespace name 'Http' does not exist in the namespace 'System.Net' (are you missing an assembly reference?) in RefitStubs.cs

This seems to happen for everything except winphone.
Note: it seems to go away if I add a reference to System.Net.Http...

Thoughts?

Refit causes TFS Builds to fail

Issue is that it errors out if the target file (the RefitSubs.cs) is read-only. TFS Team Build (and possibly other build agents) will check files out as read-only. This causes the build to fail.

Suggestion: Generate the file in-memory. Read the target file and only complain if they don't match. In the case of a build server, hopefully a local user already ran the build step and the stubs are up-to-date anyway.

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.