When is the standard model request/Answer required in the context of a REST application?

Asked

Viewed 221 times

5

If possible, let’s imagine a context where Spring Boot and JPA are used.

During the construction of some REST API, I always wonder if I should perform the standard model request/Response. For example, consider the following scenario.

Our ultimate goal is to have an API that performs scheduling registration, where a scheduling can without abstracting as the following class in Java:

public class Agendamento {

    private Autor autor;

    private String texto;
}

Assuming that each schedule necessarily has an author, using Hibernate, our Entity class would look something like:

@Entity
public class AgendamentoEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    private Autor autor;

    private String texto;

}

Thus, for the registration of a schedule, the required fields could be only the texto and the id of the author. Leading us to something like:

public class AgendamentoModelRequest {

    private Long idAutor;

    private String texto;

}

Thus, the agendamentoController would receive an object of the class AgendamentoModelRequest, which in turn would be using for a AgendamentoService, making use of a AgendamentoRepository to make the registration.

But in this case Agendamento is much like AgendamentoEntity (differs by the lack of id), as it will also be equal to AgendamentoModelReponse. Thus, we could "overload" the POJO scheduling into the context of model request/Sponse and Entity.

Is doing this necessarily a bad practice? Because that would make it a lot easier, since the context is about Agendamento, then the AgendamentoController could receive the POJO Agendamento (annotated with javax.validation/persistence Annotations and fasterxml.jackson.Annotation) and using it to be the API’s own return.

1 answer

3

Reasons for using this strategy:

  1. When you want to ensure that the interface with your API is immutable
  2. To prevent your API from behaving differently with each bank entity change, at the risk of breaking the systems that are already integrated with it
  3. To separate the responsibility of the bank entity being the same to be requested/returned to the client, containing both notes related to persistence and notes related to parse (@Table and @JsonIgnore for example).
  4. To ensure an easier way to perform layer-by-layer testing (Sliced tests) and ensure that two different layers are working as expected

I replied too this question a while ago explaining a bit of the versioning strategy of an API, which goes very much against why to use these structures.

Browser other questions tagged

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