0
0
Rest APIprogramming~5 mins

Request headers (Content-Type, Accept) in Rest API

Choose your learning style9 modes available
Introduction

Request headers tell the server what kind of data you are sending and what kind of data you want back. This helps the server understand and respond correctly.

When sending JSON data to a server, you use Content-Type to say the data is JSON.
When you want the server to send back XML instead of JSON, you use Accept to ask for XML.
When uploading a file, you use Content-Type to tell the server the file type.
When calling an API that supports multiple formats, you use Accept to specify your preferred format.
Syntax
Rest API
Content-Type: media/type
Accept: media/type

Content-Type tells the server the format of the data you are sending.

Accept tells the server the format you want in the response.

Examples
You send JSON data and want JSON back.
Rest API
Content-Type: application/json
Accept: application/json
You send form data and want an HTML page back.
Rest API
Content-Type: application/x-www-form-urlencoded
Accept: text/html
You upload files and want JSON response.
Rest API
Content-Type: multipart/form-data
Accept: application/json
Sample Program

This Python program sends JSON data to a test server with Content-Type and Accept headers set to application/json. It prints the status code, the response content type, and the JSON data the server received.

Rest API
import requests

url = 'https://httpbin.org/post'
headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
}
data = {'name': 'Alice', 'age': 30}

response = requests.post(url, json=data, headers=headers)
print(response.status_code)
print(response.headers['Content-Type'])
print(response.json()['json'])
OutputSuccess
Important Notes

Always set Content-Type when sending data so the server knows how to read it.

Use Accept to tell the server what response format you prefer, but the server may not always honor it.

Headers are case-insensitive but usually written with capital letters and hyphens.

Summary

Content-Type header tells the server the format of your request data.

Accept header tells the server what response format you want.

Setting these headers helps APIs communicate clearly and avoid errors.