Instead of using a URLConnection, you should be using an HttpClient to make a request.

A simple example might look like this:

HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(theUrl);
request.addHeader("x-api-key", apiKey);
HttpResponse response = httpclient.execute(request);
Answer from Bryan Herbst on Stack Overflow
🌐
Apidog
apidog.com › blog › pass-x-api-key-header
How to Pass x-API-key in Header?
July 31, 2025 - To pass the x-API-key in the header using Apidog, follow these steps: Step 1: Launch Apidog and open the desired project. Step 2: Create a new API endpoint or select the desired endpoint at Apidog. Step 3: Within the API endpoint request section, navigate to Headers section. Step 4: On the header parameters, enter "x-API-key" as the name.
🌐
AWS
docs.aws.amazon.com › amazon api gateway › developer guide › api gateway rest apis › distribute your rest apis to clients in api gateway › usage plans and api keys for rest apis in api gateway › choose an api key source in api gateway
Choose an API key source in API Gateway - Amazon API Gateway
To have the client submit an API key, set the value to HEADER in the previous command. ... To choose an API key source for an API by using the API Gateway REST API, call restapi:update as follows: PATCH /restapis/fugvjdxtri/ HTTP/1.1 Content-Type: application/json Host: apigateway.us-east-1.amazonaws.com X-Amz-Date: 20160603T205348Z Authorization: AWS4-HMAC-SHA256 Credential={access_key_ID}/20160603/us-east-1/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature={sig4_hash} { "patchOperations" : [ { "op" : "replace", "path" : "/apiKeySource", "value" : "HEADER" } ] }
🌐
Pirelli
developer.pirelli.com › docs › read › authorize_your_api_calls › XApiKey
Pirelli API Portal - X-Api-Key
Refer to the [Register your Application](/docs/read/Register_your_Application) section for instructions on how to get a key. ## General Use To call the resource endpoints put the key in the *X-Api-Key* HTTP header, like this:
🌐
Stoplight
blog.stoplight.io › home › api keys: api authentication methods & examples
API Keys: API Authentication Methods & Examples | Stoplight
November 10, 2023 - The most popular choice for including ... on API gateway authentication, see this post about API gateways. GET / HTTP/1.1 Host: example.com X-API-KEY: abcdef12345...
🌐
Reddit
reddit.com › r/htmx › help: correct way of sending x-api-key in headers using htmx?
r/htmx on Reddit: Help: Correct way of sending X-API-KEY in headers using HTMX?
October 23, 2024 -

Hi everyone,

First of all I am thankful to all redditors who helped me on my previous posts. And, now, I am again stuck in a situation where I would like to send X-API-KEY in headers to my API.

I am sending my X-HTTP-KEY as following:

<form autocomplete="off" id="wa-link-form"
                                hx-post="<?= $baseUrl ?>/api/create_link"
                                hx-trigger="submit"
                                hx-target="#result"
                                hx-swap="outerHTML"
                                hx-headers='{"X-API-KEY": "<?php echo htmlspecialchars($apiKey); ?>"}'
                                hx-on::after-request="clearForm(); reissueCsrfToken();">

So, I want to ask if this is the right way?

🌐
Swagger
swagger.io › docs › specification › v3_0 › authentication › api-keys
API Keys | Swagger Docs
This example defines an API key named X-API-Key sent as a request header X-API-Key: <key>. The key name ApiKeyAuth is an arbitrary name for the security scheme (not to be confused with the API key name, which is specified by the name key). The name ApiKeyAuth is used again in the security section ...
🌐
Medium
medium.com › @josiahmahachi › secure-asp-net-apis-using-x-api-key-api-keys-62d63b2b9fb0
How to secure ASP.NET APIs using x-api-key API keys | by Josiah T Mahachi | Medium
February 28, 2023 - After generating the X-API-KEY, we need to add it to each API request. This can be done by adding the X-API-KEY header to the HTTP request. Here’s an example of how to add the X-API-KEY header to an HTTP request using the HttpClient class in C#:
Find elsewhere
Top answer
1 of 1
24

Be consistent

Some may say this is unnecessary (and not too long ago I would have agreed) but these days, with so many auth protocols, if we use the Authorization header to pass an API key, it is worth informing the type too because API keys are not self-descriptive per se 1.

Why do I think it is worth it? Because nowadays supporting different authentication or/and authorization protocols has become a must-have. If we plan to use the Authorization header for all these protocols, we have to make our auth service consistent. The way to communicate what kind of token we send and what authorization protocol should be applied should go in the header too.

Authorization: Basic XXXX
Authorization: Digest XXXX
Authorization: Bearer XXXX
Authorization: ApiKey-v1 XXXX
Authorization: ApiKey-v2 XXXX

I used to don't care about this, but after working with mobile clients or sensors, in which updates were not guaranteed, I started to. I started to be more consistent in the way I implement security so that I can keep backwards compatibility. With the token's type informed I can invalidate requests from a specific set of clients (the outdated ones), add new schemes and differentiate old clients from new ones and change auth validations for one or another scheme without causing breaking changes. I also can apply specific rules in the API Gateways based on the authorization scheme. For example, I can redirect old schemes to specific versions of my web APIs which are deployed apart from the main ones.

Concerns

The problems I faced implementing my own schemes have been similar to the one commented.

On the other hand, I found a consideration that a custom Authorization scheme can be unexpected and unsupported by some clients and leads to custom code anyway

Say clients, say libraries, frameworks, reverse proxies. A custom header can be rejected or ignored. In the worse of the cases, it can also collide.

Collisions can be problematic, but all other issues are likely to be solved by tackling configurations.

Advantages

One important advantage is cache. Shared caches won't cache the header (and that's good of course) unless you say otherwise.

So Authorization or custom header?

In my experience, both take me almost the same work and time to implement, with a slight difference. I had more room for design when I implemented custom headers. However, more room for design also meant more chances to overcomplicate things or reinvent the wheel.

Technically, there could be very little or no difference between the two, but I have found the consistency to be a good feature. It provides me with clearness and understanding. In my case, adding new schemes was reduced to adding 2 new abstractions (implemented by the same concrete class): TokenHandler and TokenValidator. The Handler only checks whether the request header Authorization informs the supported scheme. The Validator is anything I need to validate the token. Altogether working from a single request filter instead of a chain of filters or a big ball of mud.


1: I find this answer to be very clear regarding API Keys

🌐
WPGetAPI
wpgetapi.com › home › api key in headers
API Key in Headers - WPGetAPI
March 11, 2024 - A lot of APIs will use an API key that is sent in the request header. The API key could be called anything, depending on the API you are using. It might be labelled ‘api_key’, ‘apikey’, ‘key’, ‘x-api-key’ or whatever the API decides to call it.
🌐
GitGuardian
docs.gitguardian.com › x-api-key
X-Api-Key | GitGuardian documentation
- text: | x-api-key = hj65_klhz/trlupok76 apikey: hj65_klhz/trlupok76 - text: | headers("x-api-key", "d1Hb1fb497XGT75989e") apikey: d1Hb1fb497XGT75989e - text: | X-ApiKey = jp1RP1c5WNtbjtcOe3IvXWKD apikey: jp1RP1c5WNtbjtcOe3IvXWKD
🌐
Apigee
docs.apigee.com › api-platform › tutorials › secure-calls-your-api-through-api-key-validation
Secure an API by requiring API keys | Apigee Edge | Apigee Docs
curl -v -H "x-apikey: API_KEY" http://ORG_NAME-test.apigee.net/helloapikey · Note that to fully complete the change, you'd also need to configure the AssignMessage policy to remove the header instead of the query parameter. For example:
🌐
AWS
docs.aws.amazon.com › amazon api gateway › developer guide › openapi extensions for api gateway › x-amazon-apigateway-api-key-source property
x-amazon-apigateway-api-key-source property - Amazon API Gateway
{ "swagger" : "2.0", "info" : { "title" : "Test1" }, "schemes" : [ "https" ], "basePath" : "/import", "x-amazon-apigateway-api-key-source" : "HEADER", .
🌐
Google
docs.cloud.google.com › application development › google cloud sdk › authentication › use api keys to access apis
Use API keys to access APIs | Authentication | Google Cloud Documentation
curl -X POST \ -H "X-goog-api-key: API_KEY" \ -H "Content-Type: application/json; charset=utf-8" \ -d @request.json \ "https://translation.googleapis.com/language/translate/v2" If you can't use the HTTP header, you can use the key query parameter. However, this method includes your API key in the URL, exposing your key to theft through URL scans. The following example shows how to use the key query parameter with a Cloud Natural Language API request for documents.analyzeEntities.
🌐
Medium
minimaldevops.com › different-ways-to-send-api-key-81c3de85cef5
Different ways to send API Key. First and foremost, the API should be… | by Minimal Devops | Medium
August 13, 2024 - This is the most common and secure method. The API key is sent as part of the request headers. ... In Postman, go to the Headers tab. Add a new header with the key x-api-key and the value as your YOUR_API_KEY.
🌐
Google Cloud
cloud.google.com › application development › apigee › secure an api by requiring api keys
Secure an API by requiring API keys | Apigee | Google Cloud
curl -v -H "x-apikey: YOUR_API_KEY" http://YOUR_ENV_GROUP_HOSTNAME/helloapikey · Note that to fully complete the change, you'd also need to configure the Assign Message policy to remove the header instead of the query parameter. For example: