Custom return in WEB API

2

Good afternoon.

I would like to know if there is any standard or good practice (independent of the programming language) for building Web APIs that allow customization of the content of the response by the client (user of this API).

Example: A web API with the following feature: link

that would return a JSON in the default:

{
    "id": "100",
    "nome": "nome do cliente 100",
    "endereco": "endereço completo do cliente 100"
}

Now imagine that in a certain client of this API, there is a functionality to build a table of clients, where it is necessary to list only the attributes "id" and "name".

One hypothetical solution would be to create another method in the API that returns only the required data. This would prevent the unnecessary transfer of data (in this case the "address" field).

However, it does not seem a good idea to clog the API with such specific methods, depending on the needs of the API clients.

Given this scenario, the question then is, is there any standard for customizing this return by the customer?

    
asked by anonymous 11.10.2016 / 22:16

2 answers

2

Usually APIs return a lot, and many of them we do not use. You can clog your API parameters or you can simply return everything. I do not see a problem in returning unnecessary data, unless it's something that the client really can not see.

    
11.10.2016 / 22:25
1

If there is any pattern I do not know, but this is quite simple to implement. You just need to have well defined how you will know when you decide to return one or another format.

Here is an example, where the logged-in user is of type UsuarioComum , if so, all data in the entity is returned, otherwise only Id and Nome are returned.

public IHttpActionResult Get(int id)
{       
    if(usuarioLogado.Tipo == TipoUsuario.UsuarioComum)
    {
        var retorno = _db.Clientes.Find(id)
                                  .Select(c => new 
                                               {
                                                    c.Id,
                                                    c.Nome,
                                                    c.Endereco
                                               });
        return Ok(retorno);
    }

    var retorno = _db.Clientes.Find(id)
                              .Select(c => new 
                                           {
                                               c.Id,
                                               c.Nome
                                           });
    return Ok(retorno);

}
    
11.10.2016 / 22:25