What is Content Type Header in REST API: Simple Explanation
Content-Type header in REST APIs tells the server or client what kind of data is being sent, like JSON or XML. It helps both sides understand how to read the message body correctly.How It Works
Imagine sending a letter to a friend. If you write it in English, your friend knows how to read it. But if you write it in a secret code, your friend needs to know the code first. The Content-Type header works like a label on the letter that says what language or format the message is in.
When a client (like a web browser or app) sends data to a server, it includes the Content-Type header to say what format the data uses. The server reads this header to understand how to process the data. For example, if the header says application/json, the server knows the data is in JSON format and can parse it accordingly.
This helps avoid confusion and errors, making sure both sides speak the same data language.
Example
This example shows how to send a JSON object with the Content-Type header in a HTTP POST request using Python's requests library.
import requests url = 'https://httpbin.org/post' headers = {'Content-Type': 'application/json'} data = '{"name": "Alice", "age": 30}' response = requests.post(url, headers=headers, data=data) print(response.json()['headers']['Content-Type'])
When to Use
Use the Content-Type header whenever you send data in the body of an HTTP request or response. It is essential when the data format is not plain text, such as JSON, XML, form data, or files.
For example, when submitting a form on a website, uploading a file, or sending JSON data to an API, the Content-Type header tells the server how to read the incoming data. Without it, the server might misinterpret the data, causing errors.
Key Points
- The
Content-Typeheader specifies the media type of the data sent. - Common values include
application/json,text/html, andmultipart/form-data. - It ensures the receiver knows how to parse the message body.
- Always set it correctly when sending data in HTTP requests or responses.