Many Relationships for Many in Restful Service

Asked

Viewed 101 times

3

I’m starting to work with Restful Services and I’m having doubts about many relationships for many. For example, suppose I have two entities Cliente and Fornecedor and that Cliente has a list of suppliers, the suppliers from whom he buys and Fornecedor own a list of customers who buy from it. Something like this

public class Cliente
{
    // Propriedades da classe Cliente

   public IList<Fornecedor> Fornecedores { get; set; }
}

public class Fornecedor
{
    // Propriedades da classe Fornecedor

   public IList<Cliente> Clientes { get; set; }
}

So if you want to expose this in a Restful service what would be the best way to do it? I thought to expose the following URL /clientes/{idCliente}/fornecedores to get suppliers from a customer and then add or remove suppliers from that customer, but I’m finding this a bad option.

Basically because the url would already exist /fornecedores that manages suppliers in general and putting this to the suppliers of each customer seems very strange to me.

That way the most indicated way to manage many relations for many in restful api’s?

2 answers

5


I see no problem with the suggested proposal.

The fact that there are two Uris /clientes/id/fornecedores and /fornecedores it doesn’t seem strange to me. In fact, it’s a common way of managing this type of relationship, as for example, /posts + /authors/id/posts, /questions + users/id/questions...

In REST and' important that the Uris are self-descriptive. Therefore, the most natural way to describe "get the customer suppliers 123" would be GET /clientes/123/fornecedores/. Similarly, the most natural way to describe "getting customers from the supplier abc" would be GET /fornecedores/abc/clientes/

  • Thank you for the @dcastro reply. And when implementing this in the ASP.NET Web API is it recommended to put the methods to deal with the objects related to a certain object in the controller of that object or make a new controller? In this case, this would put the methods to deal with suppliers in the ClientesController instead of creating a different controller.

  • 1

    @user1620696 Hm have seen it both ways... Personally, if the methods are simple, I would create a method GetFornecedores in the controller ClientesController to the Union clientes/id/fornecedores. If logic is complex, it might be worth separating the "nested Resource" methods for your own controller (e.g., FornecedoresDeClientesController).

1

I would simplify things in the api: /Customers/{id} /Suppliers{id}? customer={idcustomer}

Take care of many relationships for many. If you still don’t know, maybe you can take some advantage of some of the DDD, where there is a clear separation between subjects in the field whose life cycle is independent. In this case, you could use Aggregates to separate these parts.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.