• Stars
    star
    238
  • Rank 169,306 (Top 4 %)
  • Language
    C#
  • Created over 4 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A RESTFul operations client that serializes responses and throws meaningful exceptions for >= 400 status codes.

RESTFulSense

.NET Nuget Nuget The Standard - COMPLIANT The Standard The Standard Community

RESTFulSense

I designed & developed this library as a wrapper around the existing .NET Core HttpClient implementation to provide the following values:

  1. Meaningful Exceptions for APIs response status codes.

  2. Simplified API communications.

  3. Test-friendly implementation.

You can get RESTFulSense Nuget package by typing:

Install-Package RESTFulSense

Here's the details of what this library has to offer:

1. Meaningful Exceptions

RESTFulSense provide the following exceptions for erroring HTTP Status Codes as follows:
Status Code Exception
BadRequest 400 HttpResponseBadRequestException
Unauthorized 401 HttpResponseUnauthorizedException
PaymentRequired 402 HttpResponsePaymentRequiredException
Forbidden 403 HttpResponseForbiddenException
NotFound 404 HttpResponseNotFoundException
NotFound 404 HttpResponseUrlNotFoundException
MethodNotAllowed 405 HttpResponseMethodNotAllowedException
NotAcceptable 406 HttpResponseNotAcceptableException
ProxyAuthenticationRequired 407 HttpResponseProxyAuthenticationRequiredException
RequestTimeout 408 HttpResponseRequestTimeoutException
Conflict 409 HttpResponseConflictException
Gone 410 HttpResponseGoneException
LengthRequired 411 HttpResponseLengthRequiredException
PreconditionFailed 412 HttpResponsePreconditionFailedException
RequestEntityTooLarge 413 HttpResponseRequestEntityTooLargeException
RequestUriTooLong 414 HttpResponseRequestUriTooLongException
UnsupportedMediaType 415 HttpResponseUnsupportedMediaTypeException
RequestedRangeNotSatisfiable 416 HttpResponseRequestedRangeNotSatisfiableException
ExpectationFailed 417 HttpResponseExpectationFailedException
MisdirectedRequest 421 HttpResponseMisdirectedRequestException
UnprocessableEntity 422 HttpResponseUnprocessableEntityException
Locked 423 HttpResponseLockedException
FailedDependency 424 HttpResponseFailedDependencyException
UpgradeRequired 426 HttpResponseUpgradeRequiredException
PreconditionRequired 428 HttpResponsePreconditionRequiredException
TooManyRequests 429 HttpResponseTooManyRequestsException
RequestHeaderFieldsTooLarge 431 HttpResponseRequestHeaderFieldsTooLargeException
UnavailableForLegalReasons 451 HttpResponseUnavailableForLegalReasonsException
InternalServerError 500 HttpResponseInternalServerErrorException
NotImplemented 501 HttpResponseNotImplementedException
BadGateway 502 HttpResponseBadGatewayException
ServiceUnavailable 503 HttpResponseServiceUnavailableException
GatewayTimeout 504 HttpResponseGatewayTimeoutException
HttpVersionNotSupported 505 HttpResponseHttpVersionNotSupportedException
VariantAlsoNegotiates 506 HttpResponseVariantAlsoNegotiatesException
InsufficientStorage 507 HttpResponseInsufficientStorageException
LoopDetected 508 HttpResponseLoopDetectedException
NotExtended 510 HttpResponseNotExtendedException
NetworkAuthenticationRequired 511 HttpResponseNetworkAuthenticationRequiredException

2. Simplified API Communications

API controllers in ASP.NET Core today don't offer the full range of HTTP Codes that can be used to communicate certain events and errors to end users, in this library we managed to implement all the missing methods to communicate the full range of error codes as follows:

2.1 On Controller Level

Controller Method Code
PaymentRequired(object value) 402
MethodNotAllowed(object value) 405
NotAcceptable(object value) 406
ProxyAuthenticationRequired(object value) 407
RequestTimeout(object value) 408
Gone(object value) 410
LengthRequired(object value) 411
PreconditionFailed(object value) 412
RequestEntityTooLarge(object value) 413
RequestUriTooLong(object value) 414
UnsupportedMediaType(object value) 415
RequestedRangeNotSatisfiable(object value) 416
ExpectationFailed(object value) 417
MisdirectedRequest(object value) 421
UnprocessableEntity(object value) 422
Locked(object value) 423
FailedDependency(object value) 424
UpgradeRequired(object value) 426
PreconditionRequired(object value) 428
TooManyRequests(object value) 429
RequestHeaderFieldsTooLarge(object value) 431
UnavailableForLegalReasons(object value) 451
InternalServerError(object value) 500
NotImplemented(object value) 501
BadGateway(object value) 502
ServiceUnavailable(object value) 503
GatewayTimeout(object value) 504
HttpVersionNotSupported(object value) 505
VariantAlsoNegotiates(object value) 506
InsufficientStorage(object value) 507
LoopDetected(object value) 508
NotExtended(object value) 510
NetworkAuthenticationRequired(object value) 511

This can be achieved by simply replacing the inheritance ControllerBase in your ASP.NET Core Controller class with RESTFulController as follows:

    [ApiController]
    [Route("api/[controller]")]
    public class ContactsController : RESTFulController
    {
        ...
    }

Once that's done, you will have full access to use any of the methods above to communicate more meaningful errors to your API consumers and clients.

2.2 On Consumer Level

Passing or retrieving objects from an API should be as simple as one method call, for RESTFulSense, you don't have to worry about how to serialize your input or deserialize the API output, here's how simple it works:

2.2.1 Initialization

The initialization of the RESTFulSense Client can be done in two different ways:

2.2.1.1 HttpClientFactory Approach

In your ASP.NET Core application, you can initialize the IRESTFulApiFactoryClient in your startup.cs as follows:

services.AddHttpClient<IRESTFulApiFactoryClient, RESTFulApiFactoryClient>(client => client.BaseAddress = new Uri(YOUR_API_URL));
2.2.1.2 Basic Initialization

You can also use the RESTFulClient simple initialize in a console app for instance as follows:

var apiClient = new RESTFulApiClient();
2.2.1 Deserialization
List<Student> students = 
    await restfulApiClient.GetContentAsync<List<Student>>(relativeUrl: "api/students");
2.2.2 Serialization
Student student = 
    await restfulApiClient.PostContentAsync<Student>(relativeUrl: "api/students", content: inputStudent); 

In addition to the wrappers around API calls and serialization/deserialization, this library also provides a simplified way to execute communications without any workarounds.

For instance, to execute a PUT API call without a body, to update a status for instance, you don't have to fake a PUT body to execute a successful call, you can just do the follows:

Account activatedAccount = 
    await restfulApiClient.PutContentAsync(relativeUrl: $"api/accounts/{accountId}/activate");

3. MultipartFormDataContent support

RESTFulSense allows you to easily convert a C# class with attributes into a MultipartFormDataContent and send it as a POST request using the PostFormAsync method.

The library includes the following attributes:

Attribute Description
RESTFulByteArrayContentAttribute Specifies a byte array content type
RESTFulStreamContentAttribute Specifies a stream content type
RESTFulStringContentAttribute Specifies a string content type
RESTFulFileNameAttribute Adds a file name to the content

These attributes allow you to specify the content types and names of the form data. The RESTFulFileNameAttribute also allows you to add a file name to the content. Simply apply the attributes to your class properties and the library will handle the rest.

Here's an example usage:

public class FormUpload
{
    [RESTFulStreamContent(name: "file")]
    public Stream Stream { get; set; }

    [RESTFulStringContent(name: "purpose")]
    public string Purpose { get; set; }

    [RESTFulFileName(name: "file")]
    public string FileName { get; set; }
}

// ...

var formUpload = new FormUpload
{
    Stream = GetStream(),
    Purpose = "fine-tune",
    FileName = "SomeFile.jsonl"
};

var result = await PostFormAsync<FormUpload, ResultType>("https://example.com/upload", formUpload);

Note the linking of the FileName to the StreamContent via the name parameter in the attributes.

4. Testing-Friendly Implementation

RESTFulSense provides an interface to the API client class, to make it easier to mock and leverage dependency injection for the testability of the client consumers, here's an example:

var restfulApiClientMock = new Mock<IRestfulApiClient>();

restfulApiClient.Setup(client =>
    client.GetContentAsync<Student>(relativeUrl: $"api/students/{studentId}")
        .ReturnsAsync(student);

If you have any suggestions, comments or questions, please feel free to contact me on:

Twitter

LinkedIn

E-Mail

Huge thanks to Mr. Brian Parker @BrianLParker for his RESTfulSense Web Assembly effort.

More Repositories

1

The-Standard

This is The Standard. A collection of decades of experience in the engineering industry. I authored it to help you navigate the vast ocean of knowledge. The Standard is not perfect and never will be, and it reflects the ongoing evolution of the engineering industry. While one person may write it, it is the collection of thoughts from hundreds of engineers I've had the honor to interact with and learn from throughout my life.
1,064
star
2

OtripleS

This is an open source schooling system, dedicated to provide a better experience for schools needing a management and communication and tutoring system all in one place. This project is aiming toward directing all the software development funds and hours to families in need, the idea of the project is to allow schools to use the system as long as the software funds in the school are directed towards financially disadvantaged families and students.
C#
326
star
3

Standard.AI.OpenAI

Standard-Compliant .NET library for Open AI
C#
264
star
4

CSharpCodingStandard

This is the Standard for C# Programming language
251
star
5

PrettyBlazor

PrettyBlazor is a Blazor .NET library that enables Blazor developers to use control structures in their Blazor applications through markup without having to use obtrusive C# code to iterate or select particular fragments.
C#
105
star
6

OtripleS.Portal

C#
94
star
7

ADotNet

ADotNet is a.NET library that enables software engineers on the .NET platform to develop AzureDevOps pipelines and Git Actions in C#.
C#
92
star
8

Taarafo.Core

This API attempts to Decentralize Social Networks to De-Productize Humanity
C#
86
star
9

The-Standard-Uzbek

63
star
10

Xeption

A Better Exception for .NET
C#
56
star
11

The-Standard-Team

This is the engineering Standard for team culture, practices and code of conduct.
56
star
12

Standard.AI.Data.EntityIntelligence

.NET library to convert natural language query into SQL queries and generate results
C#
47
star
13

OData.NxT

This repository is for all the work involved in re-envisioning OData
C#
42
star
14

ODataDemo

C#
42
star
15

SharpStyles

C# .NET Library to Serialize C# objects into CSS Rules
C#
39
star
16

RESTFulLinq

RESTFulLinq is an easy way to send LINQ queries to your API fluently
C#
38
star
17

EntityIntelligence.POC

C#
37
star
18

InvisibleApi

ASP.NET Library that allows developers to add an extra layer of security on top of their existing endpoints
C#
33
star
19

EFxceptions

.NET Standard library to convert DbUpdateException into meaningful exceptions
C#
32
star
20

Taarafo.Web

C#
31
star
21

ODataWithoutEF

C#
31
star
22

SchoolEM

C#
30
star
23

LeVent

LeVent is a .NET library to manage local events in any application
C#
29
star
24

Sofee.Core

Sofee is a project that allows users to collect geo-political data such as countries, regions, languages, time zones and all kinds of different data.
C#
23
star
25

InternalMock

.NET library to mock internal private static methods in the same class that is the subject of test.
C#
23
star
26

Refugee.Core

This is an API to help support refugees everywhere around the world.
C#
19
star
27

OData3.1WithSwagger

C#
18
star
28

The-Standard-Codex

It's not enough to know the truth, you must have the courage to wield it into existence. This book will show you how.
18
star
29

ODataWithEDMAndBlazor

C#
16
star
30

POC.NuVerify

This is a POC for a public nuget packages verification
C#
14
star
31

SallyLibrary

C#
12
star
32

The-Blazor-Book

This repository will hold the content of a new book - Designing Enterprise-level Systems with Blazor
12
star
33

InternTrack.Core

C#
12
star
34

taarafo

Free Speech Reimagined
11
star
35

OData3Beta

C#
11
star
36

bVirtualization

This is a Blazor component for Virtualization that supports infinite scrolling with ANY type of data source, whether it's an API or Database or just simply a file on your computer or just in memeory!
C#
11
star
37

The-Standard-Italian

10
star
38

ContextualExperience

C#
10
star
39

GeoApi

An open source API to provide Geo Information about every city in the United States of America
C#
10
star
40

The-Standard-Azerbaijani

10
star
41

The-Standard-Journal

10
star
42

ProvisionAzureWithCSharp

C#
9
star
43

The-Standard-Arabic

9
star
44

Ezregx

A library built by engineers for humans to develop regular expressions - enjoy it!
C#
9
star
45

CulDeSacDemoApi

C#
9
star
46

blazorxreact

Blazor meets ReactJS with OfficeFabric!
HTML
7
star
47

LaQueue

LaQueue is a .NET abstraction library to allow Queue communications & testing locally
C#
7
star
48

SchoolX

Demo Mocking External Dependencies for Acceptance Tests
C#
7
star
49

AOPDemo

C#
6
star
50

anki_robot_with_azure

This is a code snippet to show how you can have Vector use Azure Cognitive Services to identify objects
Python
6
star
51

The-Standard-Spanish

Esto es El Estándar. Una colección de décadas de experiencia en la industria de la ingeniería. Mi autoría sobre El Estándar le ayudará a orientarse en el vasto océano del conocimiento. El Estándar no es perfecto y nunca lo será, y refleja la continua evolución de la industria de la ingeniería. Aunque la haya escrito una sola persona, es la recopilación de los pensamientos de cientos de ingenieros con los que he tenido el honor de interactuar y de los que he aprendido a lo largo de mi vida.
6
star
52

Discord-Dot-Net-Bot

This repo shows the simplest code to write a Discord Bot in C# .NET
C#
6
star
53

The-Standard-Systems-Design

The Standard for Systems Design & Architecture
5
star
54

ODataWithEndpointRouting3.1

C#
5
star
55

StandardGoLang

Building a simple app in Golang according to The Standard
Go
4
star
56

StandardJava

Example to demonstrate implementing The Standard in Java
Java
4
star
57

The-Standard-French

4
star
58

The-Standard-German

4
star
59

BlazorWithIAsyncEnumerableDemo

HTML
4
star
60

PrettyBlazorDemo

Demo for using PrettyBlazor
HTML
4
star
61

OData6Demo

C#
4
star
62

StandardPython

Python
4
star
63

The-Standard-Turkish

4
star
64

RockSteadyGo.Game

ShaderLab
4
star
65

ODataWithCosmosDBPart1

HTML
3
star
66

ODataWithCosmosAndBlazor

C#
3
star
67

The-Standard-Portuguese

3
star
68

EFCoreManyToMany

A quick demo to show many to many relationship with EF Core 3.1
C#
3
star
69

ODataWithDotNet5Demo

C#
3
star
70

TemporalTablesDemo

C#
3
star
71

DynamicComponentBlazorDemo

HTML
3
star
72

Standard.API.RESTFulSense

C#
3
star
73

AspNet6WithOData

C#
3
star
74

FuzzySearch

C#
3
star
75

ODataCosmosDBClient

C#
2
star
76

HiddenApiDemo

C#
2
star
77

The-Standard-Polish

2
star
78

StandardKotlin

Kotlin
2
star
79

WhenWillIBeAMillionaire

A simple calculator in Blazor.NET to give an estimate of how much monthly savings an individual needs to make to become a millionaire
HTML
2
star
80

RockSteadyGo.Core

C#
2
star
81

ABC.Core.Api

C#
2
star
82

Funcai

Experiment project to test post code to an API
JavaScript
2
star
83

InternTrack.Web

C#
2
star
84

The-Standard-Ukrainian

2
star
85

ML.NET-DEMO

C#
2
star
86

AspNetCoreWithPostgresAndOData

This repo has a demo project to show you how you can run ASP.NET Core application with Postgres and OData
C#
2
star
87

Azure-AI-Studio-Demo

This repo demonstrates working with Azure AI Studio fine-tuned instance
C#
2
star
88

JSCalculator

This is a calculator designed using HTML, CSS and JavaScript
JavaScript
1
star
89

HotReloadSimplified

1
star
90

SampleApp

C#
1
star
91

EventoShop

A project to demonstrate Scheduled Eventing
C#
1
star
92

ConDemo

C#
1
star
93

FundamentalsASPNETCore

C#
1
star
94

The-Standard-Malaysian

1
star
95

Standard.Universal.TypeScript

TypeScript
1
star
96

Benchmarking.NET

C#
1
star
97

GraphODataDemo

C#
1
star
98

The-Standard-Experiences

1
star
99

OData.Neo.Java

1
star
100

The-Tri-Nature-Of-Everything

This is an open-source book to dive into The Tri-Nature of Everything Theory.
1
star