Giter Site home page Giter Site logo

matjazbravc / refitdemo Goto Github PK

View Code? Open in Web Editor NEW
2.0 1.0 0.0 16 KB

Instead of you make your own HttpClient calls (which is a little bit low level and somewhat annoying) you can use Refit, an automatic type-safe REST library for .NET Core and Xamarin.

C# 100.00%
aspnetcore aspnetcorewebapi dotnetcore refit

refitdemo's Introduction

Refit RESTful library POC

Instead of you make your own HttpClient calls (which is a little bit low level and somewhat annoying) you can use Refit, an automatic type-safe REST library for .NET Core and Xamarin. It makes it easy to just declare the methods of a client and its associated REST API with a C# interfaces like this:

public interface ICompanyDepartmentsApi
    {
        [Post("/api/v1.1/departments/create")]
        [Headers("Authorization: Bearer")]
        Task<Department> CreateDepartment([Body] Department department);

        [Delete("/api/v1.1/departments/{id}")]
        [Headers("Authorization: Bearer")]
        Task DeleteDepartment(int id);

        [Get("/api/v1.1/departments/getall")]
        [Headers("Authorization: Bearer")]
        Task<IEnumerable<DepartmentDto>> GetAllDepartments();

        [Get("/api/v1.1/departments/{id}")]
        [Headers("Authorization: Bearer")]
        Task<Department> GetDepartment(int id);
    }

and then ask for an HttpClient that communicate that API's interface, calling it. Simply amazing.

...
private static async Task<string> GetAuthenticatedUserToken()
{
    var usersAuthenticationApi = RestService.For<ICompanyUsersApi>("http://localhost:52330");
    var user = new UserDto {Username = "johnw", Password = "test"};
    var authenticatedUser = await usersAuthenticationApi.AuthenticateUser(user);
    return authenticatedUser.Token;
}
...

// Authenticate User and retrieve token
var token = await GetAuthenticatedUserToken();

// Pass token to Refit
var usersApi = RestService.For<ICompanyUsersApi>("http://localhost:52330",
    new RefitSettings
    {
        AuthorizationHeaderValueGetter = () => Task.FromResult(token)
    });
    
var allUsers = await usersApi.GetAllUsers();
foreach (var usr in allUsers)
{
    Console.WriteLine(JsonConvert.SerializeObject(usr));
}    

What about HttpClientFactory?

Refit has now support for the ASP.Net Core 3.x HttpClientFactory. Add a reference to Refit.HttpClientFactory and call the provided extension method in your ConfigureServices method to configure your Refit interface:

// Configure Refit settings here
var settings = new RefitSettings(); 

services.AddRefitClient<IWebApi>()
        .ConfigureHttpClient(c => c.BaseAddress = new Uri("http://localhost:52330"));
        // Add additional IHttpClientBuilder chained methods as required here:
        // .AddHttpMessageHandler<MyHandler>()
        // .SetHandlerLifetime(TimeSpan.FromMinutes(5));

With Refit is really easy to make a quick strongly-typed REST Client for pretty much any API. Read more about it here.

Prerequisites

**NOTE: To make this demo up and running you have to load and run my OpenAPI.Swagger.Demo solution.

Go get Refit and play with it today. Enjoy!

Licence

Licenced under MIT. Contact me on LinkedIn.

refitdemo's People

Contributors

matjazbravc avatar

Stargazers

 avatar  avatar

Watchers

 avatar

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.