Sergei Ledvanov
Sergei Ledvanov

Reputation: 2251

REST API for GET with @RequestBody

I am trying to following best practices when creating a REST endpoint for my resource Dashboard. So I am planning to create POST for creation, PUT for update and GET for fetching the Dashboard in my spring mvc controller.

However, I have a validate API endpoint as well, that does not save nor update anything in the database, so I was planning to use the GET HTTP method for the validate endpoint. But there are a lot of parameters I need to pass to this endpoint, so I'd prefer if this would be a @RequestBody and not just usual request parameters, because GET has a limit that I can exceed.

Should I use POST instead of GET even though I am not planning to make any database changes?

@PostMapping("/dashboards/{id}/validate")
public ResponseEntity<VisualMetadata> validateVisualMetadata(@PathVariable String id,
                                                             @Valid @RequestBody DashboardDto requestDto) {
}

UPD: DashboardDto does not just have primitives such as String/long/integer, but also has nested complex data types such as Axis and Metric

class DashboardDto {
   String id;
   Axis axis;
   List<Metric> metrics;
}

Upvotes: 2

Views: 6633

Answers (1)

VoiceOfUnreason
VoiceOfUnreason

Reputation: 57259

Should I use POST instead of GET even though I am not planning to make any database changes?

Probably. Sometimes, in the HTTP method registry, you can find a less common standardized method that fits your use case. Given that there are no intended changes to resource state, you would be looking for a safe method.

I don't believe that there's a good fit for your use case.

But sending a GET request with a message body is (generally) a Bad Idea:

A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request. -- RFC 7231

Part of the point of rest is that multiple organizations can use standardized off the shelf solutions, and everything "just works". If you don't need that promise (your organization controls the client, server, and the components in between), you might be able to get away with it. At least for a time.

There is nothing inappropriate about using POST for safe requests. The intermediate components won't necessarily know that the request is safe, so it's not ideal (for instance, intermediate components won't know that it is safe to resend a request when the response is lost).

Upvotes: 3

Related Questions