Giter Club home page Giter Club logo

custardapi's Introduction

What's Custard?

NuGet

Custard is a .NET standard plugin to call web APIs intuitively. ๐Ÿ˜

Fully compatible with:

  • .NET MAUI
  • Xamarin Forms

Documentation ๐Ÿ“„

Installation

  • Package manager
    Install-Package Custard -Version 0.3.7
  • .NET CLI
    dotnet add package Custard --version 0.3.7

Custard.Service

  • Instantiate a service object:

Service yourService = new Service(string host, int port = 80, bool sslCertificate = false); 
  • Create headers

yourService.RequestHeaders.Add("Hearder", "Value "); // Do this for every headers

โš  For every method below, we recommend being very explicit with your parameters. As there are too many options for parameters, this could lead to ambiguities.

e.g: use Get(controller: theController) instead of Get(theController)

  • Call a POST method

    Parameters:

    Name Type Required
    controller string โœ”
    action string โŒ
    headers IDictionary<string, string> โŒ
    jsonBody string โŒ
    parameters string[] / IDictonary<string,string> โŒ

    Usage:

    • To return a string:
      yourService.Post (controller: controller,
                        action: action,
                        singleUseHeaders: headers,
                        jsonBody: jsonBody,
                        parameters: parameters);
    • To return a model (T is the model):
      yourService.Post<T> (controller: controller,
                           action: action,
                           singleUseHeaders: headers,
                           jsonBody: jsonBody,
                           parameters: parameters);
  • Call a PUT method

    Parameters:

    Name Type Required
    controller string โœ”
    action string โŒ
    headers IDictionary<string, string> โŒ
    jsonBody string โŒ
    parameters string[] / IDictonary<string,string> โŒ

    Usage:

    • To return a string:
      yourService.Put (controller: controller,
                       action: action,
                       singleUseHeaders: headers,
                       jsonBody: jsonBody,
                       parameters: parameters);
    • To return a model (T is the model):
      yourService.Put<T> (controller: controller,
                          action: action,
                          singleUseHeaders: headers,
                          jsonBody: jsonBody,
                          parameters: parameters);
  • Call a GET method

    Parameters:

    Name Type Required
    controller string โœ”
    action string โŒ
    headers IDictionary<string, string> โŒ
    jsonBody string โŒ
    parameters string[] / IDictonary<string,string> โŒ

    Usage:

    • To return a string:
    yourService.Get (controller: controller,
                     action: action,
                     singleUseHeaders: headers,
                     jsonBody: jsonBody,
                     parameters: parameters);
    • To return a model (T is the model):
    yourService.Get<T> (controller: controller,
                        action: action,
                        singleUseHeaders: headers,
                        jsonBody: jsonBody,
                        parameters: parameters);

Passing Parameters to your requests

Custard now supports two types of parameters:

  • Path parameters
  • Query parameters

Path parameters

To pass path parameters to your requests, you have to pass them as string[]:

E.g: for /users/api/2/3/4 we would use:

string action = "users";
string controller = "api";
string[] param = { "2", "3", "4" };
           
var resultStr = await yourService.Get(controller: controller,
                                      action: action,
                                      parameters: param);

Query parameters

To pass query parameters to your requests, you have to pass them as Dictionary<string, string>:

E.g: for /users/api?two=2&three=3&four=4 we would use:

string action = "users";
string controller = "api";

Dictionary<string, string> param = new Dictionary<string, string>
{
    { "two", "2" },
    { "three", "3" },
    { "four", "4" }
};
           
var resultStr = await yourService.Get(controller: controller,
                                      action: action,
                                      parameters: param);

โš  If you want to return a model, the HTTP response body has to be in JSON format

Cancellation Token

From v0.3.5, you can now add a cancellation token to you request.

using CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
var cancelationToken = cancellationTokenSource.Token;
//

// Act
Task task =  _wService.Get(controller: controller,
                                cancellationToken: cancelationToken);
  • Callback Error

    If needed, you can add a callback if the request faces an HTTP error. This will work with any method mentioned above. This will allow you to do an handle the error more easily. Here's how it works:
    var actualResult = await yourService.Get(controller: "todolists",
                                             singleUseHeader: headers,
                                             callbackError: (err) => 
              {
                  
              });
    • code: the error status code (HttpStatusCode).

custardapi's People

Contributors

bricefriha avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

custardapi's Issues

[Optimisation] use the response from Stream

I've heard that converting JSON responses to string and then casting it to the object is a bad practice.
The apparent performance issue that makes is that we are creating a string variable containing an entire JSON document.

this can be very taxing in terms of performances while we could just use a Stream.

Never thought about that but it super awkward in retrospect...

Http Error management

To manage HTTP errors I was thinking of adding a new callback parameter to all Service methods.

Integrate RSS reader

Description

I'm quite unsatisfied with SyndicationFeed to read and use RSS feeds, since the issues I had with the Ares project (Xamarin Forms). I truly believe this would be quite interesting to integrate an RSS parser in Custard.

Tasks

  • Convert RSS to a model
  • Give the ability to convert an RSS feed to a JSON string
  • Give the ability to deeply search an image (this one shouldn't be mandatory, a parameter in the parse method will activate it)
  • Write the unit tests

[enhancement] Add ability to send a object as a payload

Since the client always has to convert an object or array to JSON to pass it to the method, wouldn't sending the array or object directly make more sense?

Example

Current

 // Arrange
 var userToCreate = new ReqresUser
 {
     Name = "Jackson",
     Job = "Writer content",
 };
 string action = "users";
 string controller = "api";

 // Act
 var result = await _serviceReqres.Post<ReqresUser>(controller, action: action, jsonBody: JsonConvert.SerializeObject(userToCreate));

Proposal

 // Arrange
 var userToCreate = new ReqresUser
 {
     Name = "Jackson",
     Job = "Writer content",
 };
 string action = "users";
 string controller = "api";

 // Act
 var result = await _serviceReqres.Post<ReqresUser>(controller, action: action, payload: userToCreate);

[Enhancement] Add query string parameters support

For now Custard only support path parameters.
Things like:

/service/myresource/user/{user}/bicycles/{bicycleId}

The idea would be to be able to support query parameters too.
Things like:

?myparam1=123&myparam2=abc&myparam2=xyz

[Feature] Add an attribute for requests

Main goal

To simplify the process of building requests even more,

Usage

Within a class or interface, having something like:

[service.Request("Post")]
public Response MyEndpoint(QueryParameters qrParameters, object payload = null);

Using MyEndpoint( qrParameters: {{ "foo", "bar" }}); would automatically call {baseUrl}/MyEndpoint?foo=bar as POST

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.