Why is it considered bad practice to send http request meta data in the JSON payload request body itself, while preferable to use request header?

Viewed 313

I have a very simple application which needs to parse this kind of payload:

curl --location 
--request POST 'https://host.com/operation' \
--header 'Content-Type: application/json' \
--data-raw '{
    "authenticationToken": "xxxxx48cd07046d4886649d7c39171b071ca2af7e0b11a2ba2cfc5080cc01ac",
    "action": "buy",
    "product": "toy",
    "price": "12"
}'

In this service, the spec is requesting authenticationToken to be part of the request body, JSON payload. The reason is, for the web service application layer, there is the need to "only look at one place" in order to complete the business logic.

The business logic verifies the token is valid, and if so it parses the action, product, and price fields and does business logic. It responds with an error if the token is not valid. This can be done by only parsing one place, the JSON payload.

Why is this considered a bad design?

Looking at online examples, many uses the design where tokens are in the header. (but both can be seen!) Something more like:

curl --location --request POST 'https://host.com/operation' \
--header 'authenticationToken: xxxxx48cd07046d4886649d7c39171b071ca2af7e0b11a2ba2cfc5080cc01ac' \
--header 'Content-Type: application/json' \
--data-raw '{
    "action": "buy",
    "product": "toy",
    "price": "12"
}'

Why is this not better to have a design where everything can be put in one place? But rather separating the token in the header.

This is not an opinion question. I am sure there is a reason why tokens are put in the header rather than inside the body itself.

1 Answers

The resource "operation" is composed of an action, a product and a price. When creating a new operation, you then need to pass an action, a product and a price.

The token isn't part of an operation though: it's a metadata that needs to be sent alongside the request for security purposes. Technically, you don't need a token to create an operation.

Making the body of the HTTP requests and responses hold a representation of the resource(s) being dealt with, produces an arguably more elegant API, closer to what REST is all about: resources.

Even backend side, it should allow you to share DTOs across your request handlers. Most frameworks deal with security via some kinds of HTTP filters, leaving your request handlers very business-focused (as they should be).

Related