Open In App

What is an API Header?

Last Updated : 06 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

What are API Headers?

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"

Why are API Headers Used For?

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"
}

Response Information:

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.

Where Can I Find the Headers in My API Request?

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.

Formatting Headers

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

API Headers in Action

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));

Configuring Request Headers

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));

Next Article
Article Tags :

Similar Reads