Developer

Forum

 

Refit

The automatic type-safe REST library for .NET Core, Xamarin and .NET

What is refit

Strongly typed rest client 

Uses HttpClient

Declare rest api contract via c# interface

Defining a rest interface

public interface IAdvertApiV3
    {
        [Get("/api/v3/adverts/jobref/{jobref}")]
        Task<IEnumerable<Models.Response.Advert>> GetByJobRef(long jobref);

        [Get("/api/v3/adverts/{advertRef}")]
        Task<Models.Response.Advert> GetByAdvertRef(long advertRef);

        [Get("/api/v3/adverts/latest/{count}")]
        Task<List<Models.Response.Advert>> GetLatest(int count);

        [Post("/api/v3/adverts/jobrefs")]
        Task<IEnumerable<Models.Response.Advert>> PostByJobRef([Body]long[] jobRef);

        [Post("/api/v3/adverts/advertrefs")]
        Task<IEnumerable<Models.Response.Advert>> PostByAdvertRef([Body]long[] advertRefs);

        [Get("/api/v3/adverts")]
        Task<IEnumerable<long>> GetChangedAdvertsSince([Query] DateTime date);
        
        [Post("/api/v3/adverts")]
        Task<long> Post([Body]CreateAdvertRequest advert);
    }

Getting a Client

// DEPENDENCY INJECTION

var tokenCache = new TokenCache();
var apiConf = new ApiConfigurationService(config);
var refitFactory = new RefitFactory.RefitFactory(
                    apiConf, 
                    tokenCache, 
                    new HttpContextAccessor()
                   );

// Api s
services.AddTransient(x => 
    refitFactory.GetRestService<IMailApi>("MailApi")
);

USING A CLIENT

namespace AcademicWork.Gfl.Api.Controllers.Api
{
    [Produces("application/json")]
    [Route("api/gfl")]
    public class GflController : Controller
    {
        private readonly IMailService _mailService;

        public GflController( IMailService mailService)
        {
            _repository = repository ?? throw new ArgumentNullException(nameof(repository));
            _mailService = mailService;
        }

        [HttpPost()]
        public async Task<IActionResult> Post([FromBody] CreateGflRequest input)
        {
            var body = await _mailService.RenderBodyAsync(
                input.MailType,
                input.Sender, 
                input.UrlUniqueId.ToUrl(), 
                input.LoginKey
                );
            return Ok(data.ToResponse(body));
        }
}

Refit Gotchas

http://localhost/api/values?id=1&id=2

 

Very hard to get to work

 

"Work around" or better api designs

 

http://localhost/api/values?ids=1,2

(Requires pluming in MVC, come see me)

 

Or just use POST (Or Rickards user will bite U)

Refit Gotchas 2

YOU MUST HAVE A DIRECT

REFERENCE TO REFIT IN THE

SAME PROJECT AS YOU ARE GOING  TO USE IT!

 

 

Refit generate a class when you compile that is used as the concrete HttpClient!

Developer forum 2018-04-27

By fhelje

Developer forum 2018-04-27

  • 317