Introduction
Many APIs you will use are not entirely open to the public. To manage access, prevent abuse, and track usage, API providers often require you to identify your application with a unique identifier called an API key. An API key is a long, unique string of characters you include with your requests to authenticate your application with the service.
Think of it like a library card for your code. While anyone can walk into the library (the API), you need to present your library card (the API key) to the librarian (the server) before you are allowed to check out any books (access the data). It proves that you are a registered service user with permission to make requests.
Learning Goals
-
Define what an API key is and its purpose.
-
Explain why APIs use keys (e.g., authentication, rate limiting).
-
Describe how an API key is typically sent in an HTTP request header.
-
Create a Noroff API key using Postman.
Why Do APIs Use Keys?
API providers use keys for several important reasons:
-
Authentication: The primary purpose is to identify the client application making the request. It confirms that the request is coming from a known source.
-
Authorisation: The API can determine what the application is allowed to do based on the key. For example, a free-tier key might only allow access to GET requests, while a premium key might allow POST and PUT requests.
-
Rate limiting: To prevent a single application from overwhelming the server with too many requests, APIs use keys to enforce rate limits (e.g., allowing only 100 requests per minute per key). This ensures fair usage for everyone.
-
Analytics and tracking: Keys allow providers to track how their API is used. This data is valuable for improving the service, and in the case of commercial APIs, for billing purposes.
How to Use an API Key
An API key is a secret credential and should be treated like a password. It is almost always sent as part of the HTTP headers of your request.
HTTP headers are key-value pairs of metadata sent along with a request to provide additional information to the server. To send an API key, we add a specific header where the key is the header name defined by the API provider and the value is our unique API key.
The name of the header varies between APIs. Common names include:
-
Authorization
-
X-Noroff-API-Key
-
Authorization
The API’s documentation will always tell you the exact header name to use.
Basic Example (in JavaScript)
To include headers in a fetch request, we provide a second argument: an options object. This object contains a headers property, which is itself an object of our key-value pairs.
// This is a conceptual example
const url = 'https://api.example.com/protected-data';
const apiKey = 'YOUR_UNIQUE_API_KEY_HERE';
async function fetchDataWithKey() {
const options = {
method: 'GET', // GET is the default, but it's good practice to be explicit
headers: {
// The header name is determined by the API documentation
'X-Api-Key': apiKey,
},
};
const response = await fetch(url, options);
const data = await response.json();
console.log(data);
}
Practical Example: Creating a Noroff API Key
The Noroff API requires an API key for most of its endpoints. Creating a key is a multi-step process that you will perform in Postman. This process mimics how a real application would work: a user must first register and log in before they can generate credentials for an application.
Step 1: Register a User Profile
To get a key, you must first have a registered user account. We will do this by making a POST request to the register endpoint.
-
Method: POST
-
URL: https://v2.api.noroff.dev/auth/register
-
Body: In Postman, select the “Body” tab, choose the “raw” option, and select “JSON” from the dropdown. Enter your details in the following format. Your email must be a stud.noroff.no address.
{
"name": "YourUsername",
"email": "your.name@stud.noroff.no",
"password": "your_secure_password"
}
Click “Send”. A 201 Created response means you have successfully registered.
Step 2: Log In to Get an Access Token
Now, log in with your new credentials. The response will contain a temporary accessToken, which proves you are an authenticated user.
-
Method: POST
-
URL: https://v2.api.noroff.dev/auth/login
-
Body: (raw, JSON)
{
"email": "your.name@stud.noroff.no",
"password": "your_secure_password"
}
Click “Send”. The response will contain your user profile and an accessToken. Copy the entire accessToken value.
Step 3: Create the API Key
Finally, we use our accessToken to authorise the creation of a long-term API key for our application.
-
Method: POST
-
URL: https://v2.api.noroff.dev/auth/create-api-key
-
Authorisation: In Postman, go to the “Authorisation” tab. Select “Bearer Token” from the “Type” dropdown. In the “Token” field on the right, paste the accessToken you copied from the login step.
-
Send: Click “Send”.
The response will contain your new API key. The key itself is the value of the key property.
Security Best Practice: Environment Variables
In the example above, we stored our API key directly in the JavaScript code as a string:
const apiKey = 'YOUR_UNIQUE_API_KEY_HERE';
While this is fine for a quick local test, hardcoding API keys in your code is a major security risk, especially if you plan to share your code or save it online.
If you upload this code to a platform like GitHub, anyone who can view your repository can steal your API key. They could then use your key to make requests, potentially using up your rate limits, deleting your data, or incurring costs on your account.
To solve this, developers use Environment Variables.
What are Environment Variables?
Environment variables (often shortened to “env vars”) are global variables that exist outside of your application’s code. They are part of the environment in which the code runs (like your computer or a web server).
Think of environment variables like the settings menu on your phone. You don’t change the physical wiring of your phone to lower the brightness; you change a setting. Similarly, environment variables allow us to change sensitive values (like API keys) or configuration settings (like database URLs) without editing the actual code file.
Why Do We Use Them?
-
Security: This is the most important reason. By keeping API keys out of your main code files, you can safely upload your code to GitHub without exposing your secrets.
-
Flexibility: You might use a “Test API Key” on your laptop while developing, but a “Live API Key” when the website is published. Environment variables allow the code to stay the same while the keys change depending on where the code is running.
How It Works (The Concept)
In a professional development setup, this process typically involves two parts:
The .env file: Developers create a special file simply named .env in their project folder. This file contains the sensitive keys.
# Content of a typical .env file
API_KEY=my_secret_key_12345
The .gitignore file: This is a configuration file that tells Git (the version control system) to ignore specific files. By listing .env inside .gitignore, you ensure that your secret keys are never uploaded to GitHub, even if you upload the rest of your project.
Accessing Env Vars in Code
When your application runs, it looks for these variables in the environment rather than a hardcoded string.
Instead of writing this:
// ❌ UNSAFE: Hardcoded key
const apiKey = "12345-abcde-secret";
You would write code that looks something like this:
// ✅ SAFE: Reference to a variable
// (Note: The specific syntax depends on the tools you use)
const apiKey = process.env.API_KEY;
Important Note for Learners
At this stage in your learning, you might not have the tools set up to load .env files automatically yet. However, it is critical to adopt the right mindset now:
-
Be careful with GitHub: If you are pushing your lesson code to a public GitHub repository, do not include your real API key in the code.
-
Revoke leaked keys: If you accidentally upload an API key to the internet, go to the API provider’s dashboard immediately, delete (revoke) that key, and generate a new one.
Updated Basic Example
Below is the same example from earlier, but updated to use an environment variable. Notice that the sensitive key is no longer visible in the code.
.env file which should be added to your.gitignore:
# This is our secret key
API_KEY=my_secret_key_12345
Main index.js file:
// This is a conceptual example using an environment variable
const url = 'https://api.example.com/protected-data';
// ❌ OLD: const apiKey = 'YOUR_UNIQUE_API_KEY_HERE';
// ✅ NEW: We reference the variable defined in our .env file
const apiKey = process.env.API_KEY;
async function fetchDataWithKey() {
const options = {
method: 'GET',
headers: {
// The header uses the variable, not a hardcoded string
'X-Api-Key': apiKey,
},
};
const response = await fetch(url, options);
const data = await response.json();
console.log(data);
}
Because browsers cannot read .env files directly, this code typically requires a build tool (which you will learn about in future modules). For now, it is important to understand why we write it this way: to keep the secret key separate from the logic.
Copy the value of the key from the response body and save it somewhere safe, like a text file on your computer. This is your permanent API key for this course. You will need it for many future lessons and assignments.