Search code examples
resthttp-headers

HTTP headers "Accept" and "Content-Type" in a REST context


I understand that the Accept HTTP header defines a data type expected in a response sent from the server, so it's used as a response header.

My question is regarding the Content-Type, it's used by a client to define the body format of a request sent. I always used it as part of a client request, so I have a client request where I set the headers with Accept and Content-Type. And recently, I came across a project where the Content-Type is defined in the response headers (so sent by the server).

So my question is: Content-Type need to be set as part of the client request header or as part of the server response header or can it be set to both?


Solution

  • The difference can be found in the specifications, in this case RFC 7231:

    5.3.2. Accept

    The "Accept" header field can be used by user agents to specify response media types that are acceptable.


    3.1.1.5. Content-Type

    The "Content-Type" header field indicates the media type of the associated representation

    The Accept header always indicates what kind of response from the server a client can accept. Content-Type is about the content of the current request or response, depending on which kind of HTTP message it is applied.

    So if a request has no payload, you don't have to send a Content-Type request header, and the same goes for your response: no body — no header necessary.

    Some servers may require you to provide a Content-Type in a request even if the request has no payload; the server should return a 415 Unsupported Media Type response if you omit it.