Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Why send User-Agent while making API calls?

While making API calls, we send different sorts of headers like Content-Type, Accept, Authorization, etc. But, have you ever wondered why we send the User-Agent header? In this article, I’ll talk about why we send the User-Agent header while making API calls.

So, I was reading this article by Matt Kingshott the other day where he explains how to send the User-Agent HTTP header using Laravel’s HTTP client and that’s where I got to know about the practical use of the User-Agent header.

What is the User-Agent header?

Essentially,

The User-Agent request header is a characteristic string that lets servers and network peers identify the application, operating system, vendor, and/or version of the requesting user agent.

So, let’s say you’re making an API call to a third-party API and you’re making the call without specifying the User-Agent header. In such a case, the third-party API will not be able to identify the application, operating system, vendor, and/or version of the requesting user agent, etc. So, it will not be able to identify the client making the API call.

The problem

When you don’t send the User-Agent header along the problem this will create is the third-party API vendor will not be able to identify the client making the API call and the API vendor would not be able to get back to the client/company if there’s any issue with the API call.

The solution

This is where the User-Agent header comes into play. We can attach the User-Agent header to API calls where we can specify the details about the application, the version, the website, contact email, etc.

Here’s an example of doing so using JavaScript’s fetch() API.

fetch('https://some-thirdparty-api.com', {
  headers: {
    'User-Agent': 'MyApp/1.0 (https://example.com) | [email protected]'
  }
});

As you can tell, using the User-Agent header, we can specify the details about the application, version, website, and contact email. And so, the third-party API will be able to identify the client making the API call and the API provider will be able to get back to the client if there’s any issue with the API call using this information.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?