Manu Carba
Manu Carba

Reputation: 139

How can I manage my API endpoint for an entity that has other related entities?

I'm building a RESTful API with Spring. I am reading the docs and tutorials and most of them have just basic objects in their examples and I don't know how to combine all that into solving my current problem...

I don't know how to handle 2 things here:

  1. What is the best way to handle the creation of my entity with an HTTP request? Should I send the IDs of the related entities in the body, in the query params? Should I just send the entire object?
  2. In this case, if I send the IDs of the related entities separately, I believe the @Valid annotation would trigger as invalid because the body would not have the objects the model asks for (Employee and Customer, in my case).

This is the endpoint:

    @PostMapping("/orders")
    ResponseEntity<EntityModel<Order>> createOrder(@Valid @RequestBody Order order) {
        order.setStatus(Status.IN_PROGRESS);
        Order newOrder = repository.save(order);

        return ResponseEntity
            .created(linkTo(methodOn(OrderController.class).getOrder(newOrder.getId())).toUri())
            .body(assembler.toModel(newOrder));
    }

The entity I want to create and validate:

@Data
@Entity
@Table(name = "Orders")
public class Order {

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

    @NotBlank
    @NotNull
    private String description;

    @NotBlank
    @NotNull
    private Status status;

    @NotNull
    @ManyToOne
    @JoinColumn(foreignKey = @ForeignKey(name = "employee_id_fk"))
    private Employee employee;

    @NotNull
    @ManyToOne
    @JoinColumn(foreignKey = @ForeignKey(name = "customer_id_fk"))
    private Customer customer;

    protected Order() {}

    public Order(String description) {
        this.description = description;
        this.status = Status.IN_PROGRESS;
    }
}

Thanks a lot in advance for your help.

Upvotes: 0

Views: 960

Answers (1)

Romil Patel
Romil Patel

Reputation: 13727

What is the best way to handle the creation of my entity with an HTTP request? Should I send the IDs in the body, in the query params? Should I just send the entire object?

When we create a new record in the database, we don't send the Id in the request, Id will be generated automatically based on strategy defined in @GeneratedValue when you save the entity using orderRepository.save(order); You just need to pass the object with the required details that you want to save.

The ideal way to receive the payload for @RequesetBody is by using the DTOs. We may create the DTOs according to the requirements and can specify the Ids of type Long or required instead of using the whole Object such as Customer and Employee

public class OrderDTO {

    private Long id;

    @NotBlank
    @NotNull
    private String description;

    @NotBlank
    @NotNull
    private Status status;

    @NotNull
    private Long employeeId;

    @NotNull
    private Long customerId;

    protected Order() {}

    public Order(...) {
       ...
    }
}

Request payload will be:

{
    "id" : null,
    "description" : "payload using DTO",
    "status" : "yourStatus",
    "employeeId" : 1,
    "customerId" : 2
}

In this case, if I send the IDs separately, I believe the @Valid annotation would trigger as invalid because the body would not have the objects the model asks for (Employee and Customer, in my case)

@Valid validated the constraints which we have specified for modal/DTO used in @RequestBody

Upvotes: 2

Related Questions