An API header is part of the HTTP request or response that carries additional information about the request. This information can include metadata such as content type, authentication tokens, and other custom data needed by the server or client to properly process the request or response. API headers are used to provide metadata and control information in HTTP requests and responses. They are included in the HTTP message and are structured as key-value pairs. Headers can convey various types of information, such as
- Content-Type: Indicates the media type of the resource.
- Authorization: Contains credentials for authenticating the request.
- Accept: Specifies the media types that the client is willing to receive.
- User-Agent: Identifies the client software making the request.
These are the following topics that we are going to discuss below:
Basically The API headers are key-value pairs sent along with an HTTP request or response. They provide essential information about the request or response such as the format of the data being sent or received, authorization credentials, and other metadata.
Here we provide a simple related to HTTP Headers to understand the concept in a better way.
- Data format: JSON
- ETag: unique identifier for the version
- Connection: Controls whether the network connection stays open after the current transaction.
- Content-Length: The length of the response body in bytes.
Request:
GET /api/v1/resource HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer YOUR_ACCESS_TOKEN
Accept: application/json
User-Agent: MyClient/1.0
Response:
HTTP/1.1 200 OK
Date: Mon, 03 Aug 2024 12:00:00 GMT
Content-Type: application/json
Content-Length: 348
Connection: keep-alive
Cache-Control: no-cache
Set-Cookie: sessionId=abc123; Path=/; HttpOnly
ETag: "123456789"
Here we provide information about Why are API Headers Used For to understand in better way.
- Body and Response Information: Headers like Content-Type and Accept inform the server or client about the format of the data being sent or receive.
- Authorization: Headers like Authorization carry credentials such as API keys, token or any other authorization information needed to access protected resources.
- Response Caching: Header such as Cache-Control, ETag, Expires help in managing how response are catches by clients and proxies and reducing the need for repeated requests to the server.
- Response Cookies: Headers like Set-Cookie and Cookie manage session cookies and other cookie data allowing state to be maintained across multiple requests.
Body and Response Information
Here we explain about Body and Response information for understand the content in better way.
Body:
The body of an API request or response carries the actual data being transmitted. For a request this could be the data sent to the server for example form submissions, JSON payloads. For a response this is the data returned from the server like queries, results, error, error messages. Knowing how to handle the body helps in understanding what data needs to be sent and how to parse the received data.
POST /api/users HTTP/1.1
Host: geeksforgeeks.com
Content-Type: application/json
{
"name": "John Doe",
"email": "[email protected]",
"password": "securepassword"
}
This includes the data returned by the server which typically includes the response body, status code and headers.
HTTP/1.1 201 Created
Content-Type: application/json
{
"id": 123,
"name": "John Doe",
"email": "[email protected]",
"created_at": "2024-08-05T12:34:56Z"
}
Authorization
To access a protected resources you might need to include an authorization token in the header like JWT token.
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Response Caching
TO control caching you might use headers like Cache-Control and ETag
Syntax:
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: max-age=3600
ETag: "geeks123"
{
"data": "This is cached data."
}
Where:
- Cache-Control : max-age=3600 : means the response can be cached for up to 3600 seconds
- ETag : "geeks123" : is an identifier for the version of the resource, used to validate if the cached version is still valid
Response Cookies
To set a cookie for session management, you might include the Set-Cookie header in the response.
Syntax:
HTTP/1.1 200 OK
Content-Type: text/html
Set-Cookie: sessionId=geeks123; Path=/; HttpOnly; Secure; SameSite=Strict
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Welcome!</h1>
</body>
</html>
Where:
- sessionId = geeks123 is the cookie name and value
- Path=/ means the cookie is valid for the entire domain
- HttpOnly means the cookie is inaccessible to JavaScript, enhancing security.
- Secure : means the cookie is only sent over HTTPS
- SameSite=Strict : means the cookie is only sent in a first party context.
Basically API request, headers are found in the request section. They can be accessed using various tools and libraries.
- In browser developer tools: Under the Network Tab you can inspect the Headers of each request.
- In Postman: Under the Header tab of a request. Below we provide related example for you reference.
- In code: When using HTTP libraries like HttpServletRequest, WebClient in Spring Framework.
Header are formatted as key value pairs separated by a colon with each header on a new line. Below we provide related code snippets for your reference,
Example:
Content-Type: application/json
Authorization: Bearer YOUR_ACCESS_TOKEN
Below we provide an example for API Headers in Action means in source code.
Example:
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
To Configuring Request Headers follow below points.
Using Postman
Add Key-Value pairs in the Headers tab. Below we provide those examples and output image.
Using Curl
Use the -H option
curl -H "Content-Type: application/json" -H "Authorization: Bearer YOUR_ACCESS_TOKEN" https://api.example.com/data
Using Axios in JavaScript
axios.get('https://api.example.com/data', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
}
})
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
Using HttpClient in Angular
import { HttpClient, HttpHeaders } from '@angular/common/http';
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
});
this.http.get('https://api.example.com/data', { headers })
.subscribe(response => console.log(response));
Similar Reads
What is an Ethereum API?
Ethereum, a decentralized blockchain platform, has gained significant popularity due to its smart contract functionality and the ability to create Decentralized Applications (DApps). Ethereum's API (Application Programming Interface) plays a crucial role in interacting with the Ethereum network, ena
9 min read
What is an API call?
The full form of the API is Application programming interface Basically an API call is request by a software application to access data or any other service from another application or any other server. API calls are essential for enabling communication and data exchange between different software s
6 min read
What is an API Endpoint ?
The API endpoint is the specific URL where requests are sent to interact with the API. In this article, we will discuss API Endpoint their working and the differences between REST API and GraphQL endpoints. Table of Content What is an API Endpoint?How do API endpoints work?What are some best practic
7 min read
What are Headers in Web Design?
What are Headers?Headers in web design serve the purpose of the virtual storefront of a website, the actual thing that is similar to the big entrance of a physically located store. Clicked on the banner located at the top of a webpage, they are the main way of contacting the visitors, allowing them
5 min read
What is an Idempotent REST API?
Idempotent REST API means that if the same request is made a number of times then it will have the same impact as making the request just once. Lastly, the idempotent characteristic is essential for creating dependable and linear web services when clients might attempt to send the same request multi
7 min read
HTTP headers | Age
The HTTP header Age defines the times in seconds of the object that have been in the proxy cache. Usually, the age header is close to zero. It is just summoned from the server, used to calculate the proxies' current date and the date. It is a response header. Syntax: age: <delta-seconds> Direc
1 min read
HTTP headers | DNT
The HTTP DNT Header is a request header that allows users to choose if their activity could be tracked by each server and web application that they communicate with via HTTP. The generated header field is a mechanism that allows the user to opt-in or out of the tracking. Tracking allows user to expe
2 min read
HTTP headers | Accept
The HTTP Accept header is a request type header. The Accept header is used to inform the server by the client that which content type is understandable by the client expressed as MIME-types. By using the Content-negotiation the server selects a proposal of the content type and informs the client of
2 min read
HTTP headers | Early-Data
The Early-Data header is a kind of HTTP header that permits clients to send requests immediately. This ensures that there are no one or two round-trip delays that are required by Transport Layer Security (TLS) handshake to get executed. When this header is set, it indicates that the request has been
1 min read
HTTP headers | Date
Description: HTTP headers are used to pass additional information with HTTP response or HTTP request. Date HTTP header contains the date and time at which the message was generated. It is supported by all the browsers. Syntax: Date: day-name, day month year hour:minute:second GMT Directives: day-nam
2 min read