Coder Social home page Coder Social logo

sciensoft / hateoas Goto Github PK

View Code? Open in Web Editor NEW
16.0 1.0 6.0 786 KB

A library to help you achieve HATEOAS using a fluent language and lambda expression for configuring your ASP.NET Core RESTful/Web APIs. Based on the REST application architecture style, Uniform Interface, constraint Hypermedia As The Engine Of Application State (HATEOAS).

License: Apache License 2.0

C# 100.00%
hateoas restful restful-api webapi csharp aspnetcore dotnetcore

hateoas's Introduction

Sciensoft.Hateoas

Sciensoft.Hateoas Build Status Quality Gate Status Security Rating Vulnerabilities

A library to help you achieve HATEOAS using a fluent language and lambda expression for configuring your ASP.NET Core RESTful/Web APIs. Based on the REST application architecture style, Uniform Interface, constraint Hypermedia As The Engine Of Application State (HATEOAS).

The good thing is, there is no need to inheritance or additional code in your models or addition of extra result filters to support its functionality. They all come beautifully out of the box with Sciensoft.Hateoas.

Sciensoft.Hateoas threats lambda as a first-class citizen, so your configuration starts with a lambda expression. This library DO NOT enforce REST constraints or Richardson Maturity Level, and this has to be done by you, Sciensoft.Hateoas helps you only with the implementation of HATEOAS in your resource.

Learn more about RESTful API here and Lambda Expressions here.

Get Started

Sciensoft.Hateoas gets installed using Nuget package manager.

Install-Package Sciensoft.Hateoas

Or dotnet CLI dotnet add package Sciensoft.Hateoas.

Configuration

Using a fluent language, allows you to easily configure by adding the service to .NET Core dependency injection pipeline.

public void ConfigureServices(IServiceCollection services)
{
  services
    .AddMvc()
    .AddLinks(policy =>
    {
      policy
        .AddPolicy<BookViewModel>(model =>
        {
          model
            .AddSelf(m => m.Id, "This is a GET self link.")
            .AddRoute(m => m.Id, BookController.UpdateBookById)
            .AddRoute(m => m.Id, BookController.DeleteBookById)
            .AddCustomPath(m => m.Id, "Edit", method: HttpMethods.Post, message: "Edits resource")
            .AddCustomPath(m => $"/change/resource/state/?id={m.Id}", "ChangeResourceState", method: HttpMethods.Post, message: "Any operation in your resource.")
            .AddExternalUri(m => m.Id, "https://my-domain.com/api/books/", "Custom Domain External Link")
            .AddExternalUri(m => $"/search?q={m.Title}", "https://google.com", "Google Search External Links", message: "This will do a search on Google engine.");
        });
    });
}

Here is how your controller looks like, no additional injection or attribute decoration is required. Please check our Sample Project out!

[Route("api/books")]
public class BookController : ControllerBase
{
    public const string UpdateBookById = nameof(UpdateBookById);
    public const string DeleteBookById = nameof(DeleteBookById);

    [HttpGet]
    public ActionResult<IEnumerable<BookViewModel>> Get()
    { /* Code omitted for simplicity */ }

    [HttpGet("{id:guid}")]
    public ActionResult<BookViewModel> Get(Guid id)
    { /* Code omitted for simplicity */ }

    [HttpPost]
    public IActionResult Post([FromBody] BookViewModel book)
    { /* Code omitted for simplicity */ }

    [HttpPut("{id:guid}", Name = UpdateBookById)]
    public IActionResult Put(Guid id, [FromBody] BookViewModel book)
    { /* Code omitted for simplicity */ }

    [HttpDelete("{id:guid}", Name = DeleteBookById)]
    public IActionResult Delte(Guid id)
    { /* Code omitted for simplicity */ }
}

JSON Result:

{
    "Id": "8f46d29e-6c0d-4511-85e7-b1d7ae42934a",
    "Title": "The Girl Who Lived: A Thrilling Suspense Novel",
    "Author": "Christopher Greyson",
    "Tags": [
        "Fiction",
        "Crime",
        "Murder",
        "Thriller"
    ],
    "links": [
        {
            "method": "GET",
            "uri": "http://localhost:6080/api/books/83389205-b1c9-4523-a3bb-85d7255546f9",
            "relation": "Self",
            "message": "This is a GET self link."
        },
        {
            "method": "PUT",
            "uri": "http://localhost:6080/api/books/83389205-b1c9-4523-a3bb-85d7255546f9",
            "relation": "UpdateBookById"
        },
        {
            "method": "DELETE",
            "uri": "http://localhost:6080/api/books/83389205-b1c9-4523-a3bb-85d7255546f9",
            "relation": "DeleteBookById"
        },
        {
            "method": "POST",
            "uri": "http://localhost:6080/api/books/83389205-b1c9-4523-a3bb-85d7255546f9",
            "relation": "Edit",
            "message": "Edits resource"
        },
        {
            "method": "POST",
            "uri": "http://localhost:6080/change/resource/state/?id=83389205-b1c9-4523-a3bb-85d7255546f9",
            "relation": "ChangeResourceState",
            "message": "Any operation in your resource."
        },
        {
            "method": "GET",
            "uri": "https://my-domain.com/api/books/83389205-b1c9-4523-a3bb-85d7255546f9",
            "relation": "Custom Domain External Link"
        },
        {
            "method": "GET",
            "uri": "https://google.com/search?q=The Girl Beneath the Sea (Underwater Investigation Unit Book 1)",
            "relation": "Google Search External Links",
            "message": "This will do a search on Google engine."
        }
    ]
}

Features

  • Collections result with links,
  • Json.NET and System.Text.Json settings support,
  • Self-link generation,
  • Named Route link generation,
  • Custom link generation with support to path override,
  • External links configuration,
  • Configuration with Lambda Expression,
  • Attribute Routing support, and
  • Conventional Routing support.

Roadmap

  • Add support for extending link generation.
  • Add support to bypass model link generation.
  • Add support to .NET Authorization.
  • Add support to Content Negotiation type in the read-model.

Contributions

Before start contributing, check our CONTRIBUTING guideline out, also, before doing any significant change, have a look at the existing Issues and Pull Requests, one of them may be tackling the same thing.

Issues

To open an issue or even suggest a new feature, please use the Issues tab.

License

Copyright 2019 Sciensoft

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

hateoas's People

Contributors

alexzsouz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

hateoas's Issues

Support for [JsonIgnore] attribute

I've noticed that [JsonIgnore] attribute doesn't affect response when Sciensoft.Hateoas library is added to IServiceCollection.
I would like to decorate some properties with this attribute to skip serialization.
Alternate solution is to create new DTO without ignored property, but decorating one is much easier.

How to make the library work behind reverse proxies and API gateway?

In the case of reverse proxies and API gateways. The client interacts with a URL different than the URL where the API is hosted. For example, consider if my API is hosted on a URL http://api.example.com/apiresources/ which is called downstream URL and clients are supposed to interact with the URL https://gateway-apiresources.example.com which is called upstream url. Then in the response clients are always getting downstream URLs but they are supposed to get upstream URL.

While I was able to update the domain and scheme part using ForwardedHeadersMiddleware I am still not able to remove the apiresources at the end of the URL. Is there any solution other than using AddExternalUri?

Newtonsoft.Json serialization issue

On .NET Core 3 (checked on 3.1.201), when Newtonsoft.Json serializer is used, returned DTO from controllers is wrong:

{
  "Id": {
    "valueKind": 3
  },
  "CreatedOn": {
    "valueKind": 3
  },
  "CreatedBy": {
    "valueKind": 3
  },
  "LastSavedOn": {
    "valueKind": 3
  },
  "LastSavedBy": {
    "valueKind": 3
  },
  "Latitude": {
    "valueKind": 4
  },
  "Longitude": {
    "valueKind": 4
  },
  "links": [
    {
      "method": "GET",
      "uri": "http://localhost:2138/api/station/get/2af61203-e39f-4998-0be3-08d7e6a9860f",
      "relation": "Self"
    },
    {
      "method": "DELETE",
      "uri": "http://localhost:2138/api/station/delete/2af61203-e39f-4998-0be3-08d7e6a9860f",
      "relation": "DeleteStation"
    }
  ]
}

After using default serializer in .NET Core 3, i.e., System.Text.Json the DTO is serialized correctly:

{
  "Id": "2af61203-e39f-4998-0be3-08d7e6a9860f",
  "CreatedOn": "2020-04-22T10:40:06.9052182",
  "CreatedBy": "b2ac5452-e45c-4ed3-4d76-08d7dfa3a155",
  "LastSavedOn": "2020-04-22T10:40:06.9052182",
  "LastSavedBy": "b2ac5452-e45c-4ed3-4d76-08d7dfa3a155",
  "Latitude": 0,
  "Longitude": 0,
  "links": [
    {
      "method": "GET",
      "uri": "http://localhost:2138/api/station/get/2af61203-e39f-4998-0be3-08d7e6a9860f",
      "relation": "Self"
    },
    {
      "method": "DELETE",
      "uri": "http://localhost:2138/api/station/delete/2af61203-e39f-4998-0be3-08d7e6a9860f",
      "relation": "DeleteStation"
    }
  ]
}

Same DTO model in multiple route responses. Multiple policies?

To my knowledge, in current version it is not possible to add multiple policies when multiple routes return the same DTO. Let's suppose we have a DTO that returns ID when some object was created; then if the same DTO with ID is used as a response in CreateUser, CreateTeam, CreateBook, etc., all links defined within the policy will be visible everytime.

The solution: maybe an option to specify route name in policy or somehow build policies around controller method with help of expressions - not just around models?

LinkExtension.AddLink

In my oppinion LinkExtension.AddLink does not have enough flexibility. It is not possible to set custom JSON serializer options, use other methods instead of AddMvcCore like AddControllers. This may lead to braking the existing code.

The solution could be to extract parts of LinkExtension.AddLink e.g.

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<HateoasUriProvider<InMemoryPolicyRepository.SelfPolicy>, HateoasSelfUriProvider>();
services.AddTransient<HateoasUriProvider<InMemoryPolicyRepository.RoutePolicy>, HateoasRouteUriProvider>();
services.AddTransient<HateoasUriProvider<InMemoryPolicyRepository.CustomPolicy>, HateoasCustomUriProvider>();
services.AddTransient<HateoasUriProvider<InMemoryPolicyRepository.ExternalPolicy>, HateoasExternalUriProvider>();

services.AddTransient<IHateoasResultProvider, HateoasResultProvider>();

so that they can be executed in user code without calling services.AddMvcCore implicitly in LinkExtension.AddLink.

Other solution may be making the classes public.

Link generation in custom response object

It would be cool if link generation supports custom response objects.

Example:

        {
            "data": [
                {
                    "firstName": "Jhon",
                    "lastName": "Doe",
                    "links": [
                        {
                            "method": "GET",
                            "uri": "https://localhost:5001/api/person/5",
                            "relation": "Self",
                            "message": "Self link"
                        }
                    ]
                }
            ],
            "statusCode": 200,
            "message": "success"
        }

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.