What is an API Key? How It Works, Types & Best Practices

Learn via video courses
Topics Covered

What is an API Key? How It Works, Types & Best Practices

If you have ever integrated a payment gateway, a weather service, or a map into your application, you have probably used an API key. It is one of the simplest and most common ways to authenticate an application to an API.

In this guide, you will learn the API key meaning, how an API key works, the different types of API keys, how API keys differ from tokens and OAuth, and the security best practices every developer should follow.

If you are building or consuming REST APIs, you may also want to read our guide on REST APIs in Django to see how APIs are structured in real web frameworks.


API Key Meaning (Simple Definition)

An API key is a unique string that identifies and authenticates an application or project when it calls an API. Think of it as a username and password combined into a single token that proves the caller is allowed to use the service.
API keys are usually long, random strings that look like this:
AIzaSyD-1234567890abcdefghijklmnopqrstuvwxyz

When an application sends a request to an API, it includes the key. The server checks the key against its database, validates the caller, and decides what actions or data the caller is permitted to access.
API keys are commonly used for:

  • Identifying which application is making the request
  • Tracking API usage for billing or rate limiting
  • Enforcing access control and permissions
  • Blocking abusive or unauthorised callers

While API keys are simple to use, they are not the most secure authentication method by themselves. They are best suited for low-risk, server-to-server integrations where exposure can be controlled.

How Does an API Key Work?

The working of an API key is straightforward and follows a clear request-response cycle.

Step 1: Register an application

The developer signs up with the API provider and creates an application. The provider generates a unique API key and assigns it to that project.

Step 2: Include the key in every request

When the application makes an API request, it includes the key in the HTTP header, query string, or request body. The most common and secure way is to use a header.
Example HTTP GET request with an API key in the header:
GET /v1/weather?city=Mumbai HTTP/1.1
Host: api.example-weather.com
Authorization: Bearer YOUR_API_KEY_HERE

Alternatively, the key may be sent as a custom header:
GET /v1/weather?city=Mumbai HTTP/1.1
Host: api.example-weather.com
X-API-Key: YOUR_API_KEY_HERE

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

Step 3: Server validates the key

The API server receives the request, extracts the key, and checks whether it is valid, active, and within its allowed usage limits.

Step 4: Access is granted or denied

If the key is valid, the server processes the request and returns the data. If the key is invalid, expired, or over its quota, the server returns an error such as 401 Unauthorized or 403 Forbidden.

To understand the underlying protocol, read our guide on the Hypertext Transfer Protocol.

If you want to learn backend development in a structured way, explore the Scaler courses available for beginners and professionals.

API Key vs Token vs OAuth

API keys, tokens, and OAuth are all used to control access to APIs, but they serve different purposes and offer different levels of security.
An API key identifies the calling application. It is usually long-lived and applies to the entire project.

A token (such as a JWT or session token) typically identifies a specific user or session. Tokens are often short-lived and may carry information about what the user is allowed to do.

OAuth is an authorisation framework that allows a user to grant a third-party application limited access to their account without sharing their password. It is commonly used for "Login with Google" or "Connect to GitHub" features.

API Key vs Token vs OAuth Comparison Table

FeatureAPI KeyTokenOAuth
IdentifiesApplication or projectUser or sessionAuthorised third-party app
Typical lifetimeLong-lived, sometimes never expiresShort-lived, minutes to hoursShort-lived access tokens with refresh tokens
ScopeUsually broad for the projectCan be scoped to user permissionsFine-grained, user-controlled scopes
Use caseServer-to-server APIs, public dataSession management, user-specific APIsDelegated access, social login
SecurityLower; bearer credentialModerate; can be revoked per userHigher; user consent and limited scopes
ExampleGoogle Maps API keyJWT session tokenSign in with Google

For a deeper look at authentication mechanisms, see our article on challenge-response authentication.

Types of API Keys

API keys can be classified based on where they are used and what level of access they grant.

Public API Keys (Client-Side Keys)

Public API keys are designed to be used in client-side applications such as mobile apps or JavaScript frontends. They usually grant read-only access to public data and are restricted by domain, referrer, or IP address.
Examples:

  • Google Maps API key embedded in a website
  • Weather widget API key visible in frontend code
  • Analytics tracking key

Because these keys are exposed to users, they should only allow limited, low-risk operations.

Secret API Keys (Server-Side Keys)

Secret API keys are meant to be stored on a secure server and never exposed to end users. They are used for sensitive operations such as writing data, processing payments, or accessing private information.
Examples:

  • Stripe secret key for processing payments
  • AWS secret access key for cloud services
  • SendGrid API key for sending emails

These keys must be protected carefully. If leaked, they can cause financial loss, data breaches, or service abuse.

Read-Only vs Read-Write Keys

Some providers allow you to create keys with different scopes:

  • Read-only key: Can fetch data but cannot modify anything
  • Read-write key: Can create, update, or delete data

Using the principle of least privilege, you should always give a key only the permissions it needs.
For a broader explanation of authentication and authorisation in web frameworks, read our guide on authentication and authorization in Express.js.

Free Courses by top Scaler instructors
Python Course for Beginners With Certification: Mastering the Essentials
Java Course - Mastering the Fundamentals
DBMS Course - Master the Fundamentals and Advanced Concepts
JavaScript Course With Certification: Unlocking the Power of JavaScript
C++ Course: Learn the Essentials
Python and SQL for Data Science Course
Python Course for Beginners With Certification: Mastering the Essentials
Java Course - Mastering the Fundamentals
DBMS Course - Master the Fundamentals and Advanced Concepts
JavaScript Course With Certification: Unlocking the Power of JavaScript
C++ Course: Learn the Essentials
Python and SQL for Data Science Course

Security Risks of API Keys

API keys are convenient, but they come with significant security risks if not handled properly.

API keys are bearer credentials

Whoever holds the key can use it. There is no additional password or verification step. This means a leaked key is just as dangerous as a leaked password.

Keys can be leaked in repositories

Developers often accidentally commit API keys to GitHub, where they can be found by attackers scanning public repositories. This is one of the most common causes of API key misuse.

Hard-coded keys in frontend code

Putting secret keys in client-side JavaScript or mobile apps exposes them to anyone who inspects the code. Even obfuscation is not a secure way to protect a key.

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data
Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more

Unexpected charges and abuse

If an attacker obtains a key with a paid service, they may use it to make thousands of requests, causing unexpected bills or exhausting rate limits.

Lack of fine-grained control

API keys usually grant broad access to a project. If one key is compromised, the attacker may gain access to everything that key is allowed to do.

To understand the wider security landscape, read our introduction to what is cyber security. The OWASP API Security Project also documents the top risks facing APIs today: OWASP API Security.

API Key Best Practices

Following best practices can greatly reduce the risk of API key misuse. Here is a checklist every developer should use.

1. Store keys in environment variables or secrets managers

Never hard-code API keys in your source code. Use environment variables, or better yet, a secrets manager such as AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault.
import os
api_key = os.environ.get("API_KEY")

2. Use HTTPS only

Always send API keys over HTTPS, never HTTP. Without encryption, keys can be intercepted in transit.

3. Restrict key permissions

Apply the principle of least privilege. Give each key only the permissions it needs. If a key only reads data, do not make it a read-write key.

4. Restrict by IP address or referrer

Many API providers allow you to restrict where a key can be used from. Limit keys to known server IP addresses or allowed domains.

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

5. Rotate keys regularly

Set a schedule for rotating API keys. If you suspect a leak, revoke the key immediately and generate a new one.

6. Delete unused keys

Old or unused keys are forgotten attack surfaces. Remove them from your account once they are no longer needed.

7. Monitor usage and set alerts

Keep an eye on API usage dashboards. Unexpected spikes in traffic may indicate that a key has been compromised.

8. Separate production and development keys

Never use production keys in development or testing environments. Use separate keys for each environment to limit blast radius.

Google Cloud provides detailed recommendations on creating and securing API keys: Google Cloud API Key Best Practices.

For structured learning in backend engineering and security, consider the Scaler Academy.

How to Get and Use an API Key (Example)

Here is a practical example of how to obtain and use an API key with a public API.

Step 1: Sign up and create an app

Go to the API provider’s developer portal, create an account, and register a new application or project.

Step 2: Generate the API key

After registering, the provider will generate an API key. Copy it immediately and store it securely. Most providers show the key only once.

Step 3: Make a request using the key

Below is a Python example using the requests library to call a weather API with an API key.
import requests
import os

api_key = os.environ.get("WEATHER_API_KEY")
city = "Mumbai"
url = f"https://api.example-weather.com/v1/current?city={city}\&api\_key={api\_key}"

response = requests.get(url)

if response.status_code == 200:
data = response.json()
print(f"Temperature in {city}: {data['temperature']}°C")
else:
print(f"Error: {response.status_code}")

In production, prefer sending the key in a header rather than the URL query string, because URLs can be logged by servers and browsers.
headers = {"X-API-Key": api_key}
response = requests.get(url, headers=headers)

If you are working with frontend frameworks, our free React.js course can help you understand how to build API-driven user interfaces securely.

Conclusion

An API key is a simple but powerful way to authenticate an application to an API. It identifies the caller, enables usage tracking, and enforces access control. However, because API keys are bearer credentials, they must be handled with care.

To use API keys safely, store them in environment variables or secrets managers, send them only over HTTPS, restrict their permissions, rotate them regularly, and never expose secret keys in client-side code. For more sensitive or user-specific scenarios, consider using tokens or OAuth instead of plain API keys.

If you want to keep learning, explore the Scaler Academy, browse all Scaler courses, or check out our free React.js course to see how APIs connect to modern frontends.

FAQs

Q1. What is an API key?

An API key is a unique identifier that authenticates and authorises an application when it calls an API. It acts like a password for the service, allowing the provider to identify which project is making the request and control what that project is allowed to do. API keys are commonly used for tracking usage, enforcing rate limits, and blocking unauthorised callers. They are usually long, random strings generated by the API provider.

Q2. How does an API key work?

When an application makes a request to an API, it includes the API key in the HTTP header, query string, or request body. The server receives the request, extracts the key, and validates it against its database. If the key is valid and active, the server processes the request and returns the data. If the key is invalid, expired, or over its quota, the server returns an error such as 401 Unauthorized or 403 Forbidden.

Q3. What is the difference between an API key and a token?

An API key identifies the calling application or project and is usually long-lived. A token, such as a JWT or OAuth access token, identifies a specific user or session and is usually short-lived. Tokens often carry fine-grained permissions and can be revoked per user. API keys are simpler but less secure, while tokens are better suited for user-specific or sensitive operations.

Q4. Are API keys secure?

API keys are secure only when handled correctly. They are bearer credentials, meaning anyone who has the key can use it. Risks include leaking keys in public repositories, exposing them in frontend code, and sending them over unencrypted HTTP. To keep them secure, store keys in environment variables or secrets managers, use HTTPS, restrict permissions, and rotate keys regularly.

Q5. Where should I store API keys?

API keys should always be stored in environment variables or a dedicated secrets manager. Environment variables keep keys out of source code, while secrets managers such as AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault provide encryption, access control, and auditing. Never hard-code keys in your application or commit them to version control, especially public repositories.

Q6. What are the types of API keys?

The main types of API keys are public keys and secret keys. Public keys are designed for client-side use and typically allow read-only access to public data. Secret keys are meant for server-side use and grant access to sensitive or write operations. Some providers also allow you to create read-only and read-write keys, or restrict keys by IP address and referrer.