All Projects → lucassklp → Rx.Http

lucassklp / Rx.Http

Licence: MIT license
A reactive way to make HTTP Request in .NET Core 🚀

Programming Languages

C#
18002 projects

Projects that are alternatives of or similar to Rx.Http

Awesome Reactive Programming
A repository for sharing all the resources available on Reactive Programming and Reactive Systems
Stars: ✭ 163 (+162.9%)
Mutual labels:  reactivex, reactive, reactive-streams, reactive-programming
Flutter validation login form bloc pattern rxdart
[Functional reactive programming (FRP)]💧 💧 💧 [Pure RxDart] Validation login form by using the BLoC pattern with RxDart - A new Flutter project featuring a faked authentication interface to demonstrate validation. Implemented with BloC pattern.
Stars: ✭ 45 (-27.42%)
Mutual labels:  reactivex, reactive-streams, reactive-programming, rx
Rxdownloader
- Reactive Extension Library for Android to download files
Stars: ✭ 40 (-35.48%)
Mutual labels:  reactivex, reactive, reactive-streams, reactive-programming
flutter-form-with-validation-BLOC
This form and validation functions are created by using the BLOC pattern with RxDart instead of using StatefulWidget
Stars: ✭ 63 (+1.61%)
Mutual labels:  reactivex, reactive-streams, reactive-programming, rx
Reactive Ms Example
An educational project to learn reactive programming with Spring 5
Stars: ✭ 157 (+153.23%)
Mutual labels:  reactive, reactive-streams, reactive-programming
purescript-outwatch
A functional and reactive UI framework based on Rx and VirtualDom
Stars: ✭ 33 (-46.77%)
Mutual labels:  reactivex, reactive, rx
Awesome Rxjs
A collection of awesome RxJS resources
Stars: ✭ 314 (+406.45%)
Mutual labels:  reactivex, reactive, reactive-programming
Monix
Asynchronous, Reactive Programming for Scala and Scala.js.
Stars: ✭ 1,819 (+2833.87%)
Mutual labels:  reactivex, reactive-streams, reactive-programming
Rsocket Rpc Java
Standard RSocket RPC Java Implementation
Stars: ✭ 126 (+103.23%)
Mutual labels:  reactive, reactive-streams, reactive-programming
Dynamicdata
Reactive collections based on Rx.Net
Stars: ✭ 1,083 (+1646.77%)
Mutual labels:  reactivex, reactive-programming, rx
mongo-images
Ever wonder how you can create a full stack reactive application that also saves images? Well look no further! We've got Spring Webflux, Reactive Mongo Streams with GridFS, and Angular5!
Stars: ✭ 12 (-80.65%)
Mutual labels:  reactivex, reactive-streams, reactive-programming
RxJava-Codelab
Codelab project for demonstration of RxJava features
Stars: ✭ 44 (-29.03%)
Mutual labels:  reactivex, reactive, reactive-programming
Play Ws
Standalone Play WS, an async HTTP client with fluent API
Stars: ✭ 190 (+206.45%)
Mutual labels:  reactive, reactive-streams, http-client
springboot-rsocketjwt-example
Example of using JWT with RSocket and Spring Boot
Stars: ✭ 26 (-58.06%)
Mutual labels:  reactive, reactive-streams, reactive-programming
Rxjava2 Extras
Utilities for use with RxJava 2
Stars: ✭ 167 (+169.35%)
Mutual labels:  reactivex, reactive, reactive-streams
KotlinReactiveMS
An educational project to learn reactive programming with Spring 5 and Kotlin
Stars: ✭ 33 (-46.77%)
Mutual labels:  reactive, reactive-streams, reactive-programming
Ayanami
🍭 A better way to react with state
Stars: ✭ 129 (+108.06%)
Mutual labels:  reactivex, reactive, reactive-programming
Rxjava2 Jdbc
RxJava2 integration with JDBC including Non-blocking Connection Pools
Stars: ✭ 360 (+480.65%)
Mutual labels:  reactive, reactive-streams, reactive-programming
Rxcombine
Bi-directional type bridging between RxSwift and Apple's Combine framework
Stars: ✭ 741 (+1095.16%)
Mutual labels:  reactive, reactive-streams, reactive-programming
Pharmacist
Builds observables from events.
Stars: ✭ 221 (+256.45%)
Mutual labels:  reactivex, reactive-programming, rx

nuget nuget version

A lightweight library that is inpired in Angular 2+ Http Client built on top of .NET Http Client that help programmers to make asynchronous http requests.

Installation

If you are using Package Manager:

Install-Package Rx.Http -Version 2.0.1

If you are using .NET CLI

dotnet add package Rx.Http --version 2.0.1

Example of use

using Rx.Http;
using System.Reactive.Linq;

public class Program
{
    public static async void Main()
    {
        //Initialize the RxHttpClient
        var http = RxHttpClient.Create();

        //Retrieve a list of To-Do item and print the title of each element asynchronously
        http.Get<List<Todo>>("https://jsonplaceholder.typicode.com/todos/").Subscribe(items => {
            items.ForEach(item => Console.WriteLine(item.title));
        });

        //Making the same request using await
        List<Todo> response = await http.Get<List<Todo>>("https://jsonplaceholder.typicode.com/todos/");
    }
}

Options

You can setup your request by using options. It make possible you set query strings, headers and your custom serializer and deserializer for your request and response.

Let's dive in options

http.Get<List<Todo>>("https://jsonplaceholder.typicode.com/todos/", options =>
{
    options.AddHeader(new {
            Authorization = "Bearer <token>"
            Accept = "application/json"
        })
        .AddQueryString(new {
            name = "John Doe",
            index = 1
        });
});

HttpMediaType

The media type represents a interface that is used to translate a mime type to a object (serializing and deserializing).

It's called when you provide a type when you call a request like that:

var url = "https://myapi.com/names/";
var parameters = new 
{
    Name = "Lucas"
};
http.Post<List<string>>(url, parameters)
//       ^^^^^^^^^^^^^

In this example, you're sending an object which contains a property "Name" and a value "Lucas" and you're expecting to receive a List<string> from server.

Suppose that the server only does accept XML and reply the request using the CSV format. So, we have to convert the "parameter" object to XML and convert the server reply to List<string> right? That's why we have the interfaces IHttpMediaTypeSerializer and IHttpMediaTypeDeserializer.

You could create XmlHttpMediaType and CsvHttpMediaType which implements IHttpMediaTypeSerializer and IHttpMediaTypeDeserializer to solve this issue. The final code would be like that.

var url = "https://myapi.com/names/";
var parameters = new 
{
    Name = "Lucas"
};
http.Get<List<string>>(url, parameters, options =>
{
    options.SetRequestMediaType(new XmlHttpMediaType())
        .SetResponseMediaType(new CsvHttpMediaType())
});

RequestMediaType is used to serialize your body content when you are making a request. It's only called when you provide type on Generic. By default is used JsonHttpMediaType

ResponseMediaType is used to deserialize the response from server. By default is used JsonHttpMediaType

Consumers

A consumer is defined as a service that have common behavior for the requests. You can encapsulate the logic of all those requests in a easy way. The main advantage of using consumers is to abstract the HTTP request and its implementation details, and only work with the results from it. The concept is very similar to FeignClient interface from Spring Cloud

Interceptors

The interceptors are a pre-processing unit that changes the request before it happens. It can be usefull set a standard for all requests.

Example of use

In this example, we need to provide the api key for all requests to The Movie Database API

The code above shows how to use Consumers and Interceptors.

    public class TheMovieDatabaseConsumer : RxHttpClient
    {
        public TheMovieDatabaseConsumer(HttpClient httpClient): base(httpClient, null)
        {
            httpClient.BaseAddress = new Uri(@"https://api.themoviedb.org/3/");
            RequestInterceptors.Add(new TheMovieDatabaseInterceptor());
        }

        public IObservable<Movies> ListMovies() => Get<Movies>("movie/popular");
    }

    internal class TheMovieDatabaseInterceptor : RxRequestInterceptor
    {
        public void Intercept(RxHttpRequestOptions request)
        {
            request.AddQueryString("api_key", "eb7b25db28349bd4eef1498a5be9842f");
        }
    }

RxHttpRequestException

This exception is threw when the server reply with a HTTP Status different of 2xx. There's two ways to handle this exception:

    var url = @"https://jsonplaceholder.typicode.com/this_page_dont_exist_hehehe/";

    //With traditional try-catch block
    try
    {
        var todos = await http.Get<List<Todo>>(url);
    }
    catch(RxHttpRequestException ex)
    {
        HttpResponseMessage response = ex.Response;
        //...
    }

    //Or using reactive way
    http.Get<List<Todo>>(url).Subscribe(response =>
    {
        //...
    }, exception =>
    {
        HttpResponseMessage response = (exception as RxHttpRequestException)?.Response;
        //...
    })

Working with Dependency Injection

Is strongly recommended to use DI (Dependency Injection) with Rx.Http, because of HttpClientFactory, that improves HttpClient performance. For that, you must do the following:

public void ConfigureServices(ServiceCollection services)
{
    services.UseRxHttp();
    services.AddSingleton<JsonPlaceHolderConsumer>();
}

Logging

You can implement your own custom logging mechanism by implementing the interface RxHttpLogger. We provide a built-in logging mechanism called "RxHttpDefaultLogger". In case you don't have Microsoft.Extensions.Logging added on your project you can use RxHttpConsoleLogger

Here is a example that show how to use RxHttpDefaultLogger mechanism. If you have a custom logging mechanism you must replace RxHttpDefaultLogging for your class implementation.

private static void ConfigureServices(ServiceCollection services)
{
    services.AddRxHttpLogger<RxHttpDefaultLogger>();
}

Global Settings

You can setup default settings by setting the RxHttp.Default like the example below:

RxHttp.Default.RequestMediaType = new JsonHttpMediaType(new NewtonsoftJsonSerializer());
RxHttp.Default.ResponseMediaType = new JsonHttpMediaType(new NewtonsoftJsonSerializer())

Save response to file (Download)

You can also download a file using Rx.Http with a code like that:

var fileName = $"mysql-installer-web-community-8.0.22.0.msi";
var directory = Directory.GetCurrentDirectory();
var path = Path.Combine(directory, fileName);
await http.Get($@"https://dev.mysql.com/get/Downloads/MySQLInstaller/{fileName}")
    .ToFile(path); // Save response to path (download)

Navigator

The navigator works like a RxHttpClient, but it manage cookies automatically. This is useful when you want to keep session information when you make your requests. Suppose that mysite handles the session with cookies and you want to keep your session, so you can do like that:

var navigator = RxNavigator.Create();
navigator.Post("https://www.mysite.com/login", new 
{
    Login = "myLogin",
    Password = "myPass"
});

navigator.Post("https://www.mysite.com/create/task", new 
{
    Title = "myTitle",
    Description = "myDescription",
    Date = DateTime.Now
});

Note that you did nothing about cookies but could call the endpoint to create a new task using this session.

Convert to HTML Document

Suppose that you need to get a specific value from a HTML Element (for example, a label, a link or a div). Rx.Http is integrated with HtmlAgilityPack.NetCore. It can be done by calling the Extension Method called AsHtmlDocument().

🔥 Pro Tip: It can be used with RxNavigator to automatize some tasks!

Roadmap

Version 1.x

  • Reactive GET, POST, PUT DELETE Http Methods
  • Built-in JSON serializing and deserializing (using Newtonsoft.Json)
  • Support for custom serializing and deserializing
  • Logging
  • Consumers and Interceptors implementation
  • Error handling
  • Native support for x-www-form-urlencoded and form-data

Version 2.x

  • Global settings
  • ASP.Net Core native integration (Dependency Injection)
  • Save response to file (download)
  • Provide a alternative for built-in Json serializer: System.Text.Json.JsonSerializer of .NET Core 3
  • Implement cancellation token funcionality
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].