PYTHON FOR AI • LESSON 5

API Authentication

Many APIs are not publicly accessible. They require you to prove who you are before they allow you to access their data or services. This process is called API authentication.

CORE IDEA

API authentication proves that your application is allowed to use an API.

The most common approach for beginners is an API key. You receive a secret key from the API provider and send it with your request.

01

What Is API Authentication?

Imagine a private building.

You cannot simply walk inside. You need some form of identification.

Your Application
       ↓
"I want to access this API"
       ↓
Authentication
       ↓
"Are you allowed?"
       ↓
API Response

API authentication works in a similar way. The API checks whether your request has valid credentials.

02

API Keys

An API key is a secret value provided by an API provider that identifies and authorizes your application.

A key might look like this:

sk_example_123456789abcdef

This is only an example. Never use a real API key in your source code or publish it on GitHub.

Sending an API Key in a Header

import requests

api_key = "YOUR_API_KEY"

headers = {
    "X-API-Key": api_key
}

response = requests.get(
    "https://api.example.com/products",
    headers=headers
)

print(response.json())

The important part is that the key is included in the HTTP request headers.

03

Bearer Tokens

Another very common authentication method is a Bearer token.

The token is normally sent in the Authorization header.

Authorization: Bearer YOUR_TOKEN

In Python:

import requests

token = "YOUR_ACCESS_TOKEN"

headers = {
    "Authorization": f"Bearer {token}"
}

response = requests.get(
    "https://api.example.com/products",
    headers=headers
)

print(response.json())

The word Bearer tells the server that the value following it is an access token.

04

API Key vs Access Token

These terms are sometimes used interchangeably in casual discussions, but they are not necessarily the same thing.

API Key
    ↓
Usually identifies an application/client

Access Token
    ↓
Usually represents permission to access resources

The exact authentication mechanism depends on the API. Always follow that API's documentation.

05

API Key in Query Parameters

Some APIs accept the API key as a query parameter.

https://api.example.com/products?api_key=YOUR_API_KEY

With Python:

import requests

params = {
    "api_key": "YOUR_API_KEY"
}

response = requests.get(
    "https://api.example.com/products",
    params=params
)

print(response.json())

However, if an API supports authentication through headers, that is generally preferable because query strings can be exposed through URLs and logs.

06

Never Hardcode Secrets

This is one of the most important rules when working with APIs.

Do not do this:

api_key = "sk_real_secret_key_here"

If this code is pushed to GitHub, your secret could be exposed.

Instead, store secrets in environment variables.

.env File

API_KEY=your_secret_key

Then Python can read it using the os module:

import os

api_key = os.getenv("API_KEY")

print(api_key)

For real projects, the .env file should normally be excluded from Git using .gitignore.

07

Using python-dotenv

A common development setup is to use a .env file together with the python-dotenv package.

pip install python-dotenv

Create:

.env
API_KEY=your_secret_key

Then:

import os

from dotenv import load_dotenv


load_dotenv()

api_key = os.getenv("API_KEY")

print(api_key)

Now your secret is separated from your Python source code.

08

Build an Authenticated Request

Now combine environment variables with the Requests library.

import os
import requests

from dotenv import load_dotenv


load_dotenv()


api_key = os.getenv("API_KEY")


headers = {
    "X-API-Key": api_key
}


response = requests.get(
    "https://api.example.com/products",
    headers=headers,
    timeout=10
)


response.raise_for_status()


data = response.json()

print(data)

The complete flow is:

.env
 ↓
API_KEY
 ↓
Python
 ↓
HTTP Header
 ↓
REST API
 ↓
Authentication Check
 ↓
JSON Response
09

What Happens When Authentication Fails?

If your credentials are missing or invalid, the API can reject your request.

A common response is:

401 Unauthorized

For example:

response = requests.get(
    url,
    headers=headers
)

print(response.status_code)
401

This usually means the API did not accept your authentication credentials.

10

401 vs 403

These two status codes are easy to confuse.

401 Unauthorized
        ↓
Authentication is missing
or invalid


403 Forbidden
        ↓
Authentication may be valid,
but access is not allowed

For example, a valid user might authenticate correctly but still not have permission to access an admin-only endpoint.

11

OAuth

Some APIs use OAuth when applications need delegated access to resources.

Instead of simply giving your application a permanent password, OAuth commonly uses access tokens and a controlled authorization flow.

User
 ↓
Authorization
 ↓
Authorization Server
 ↓
Access Token
 ↓
Your Application
 ↓
API

You do not need to memorize the complete OAuth flow yet. The important idea is that OAuth is a token-based authorization framework commonly used for delegated access.

12

API Authentication in AI

Authentication becomes extremely important when you start working with AI APIs.

For example, an AI application may need a secret credential before it can send requests to an AI service.

Your Python AI Application
          ↓
      API Key / Token
          ↓
       HTTP Request
          ↓
       AI Service
          ↓
       JSON Response
          ↓
     Python Application

This same pattern will appear later when you work with LLM APIs, embeddings, RAG applications, and other AI services.

13

Mini Project — Authenticated API Client

Build a small Python client that reads an API key from an environment variable and uses it to call an API.

import os
import requests

from dotenv import load_dotenv


load_dotenv()


API_KEY = os.getenv("API_KEY")


if not API_KEY:
    raise ValueError(
        "API_KEY is not configured"
    )


headers = {
    "X-API-Key": API_KEY
}


url = "https://api.example.com/products"


response = requests.get(
    url,
    headers=headers,
    timeout=10
)


if response.status_code == 401:

    print("Authentication failed.")

elif response.status_code == 403:

    print("You do not have permission.")

else:

    response.raise_for_status()

    data = response.json()

    print(data)
1. Load environment variables
            ↓
2. Read API key
            ↓
3. Check API key exists
            ↓
4. Add key to headers
            ↓
5. Send API request
            ↓
6. Check authentication
            ↓
7. Read JSON response
14

API Security Rules

Follow these rules when working with API credentials.

  • Never hardcode real API keys in source code.
  • Never commit secrets to GitHub.
  • Use environment variables for local development.
  • Add secret files such as .env to .gitignore.
  • Never share API keys in screenshots or tutorials.
  • Use HTTPS when communicating with APIs.
  • Use the minimum permissions required by the API.
  • Rotate compromised credentials immediately.
15

What You Learned

  • What API authentication means
  • API keys
  • Bearer tokens
  • Authorization headers
  • Authentication using query parameters
  • Environment variables
  • Using python-dotenv
  • HTTP 401 errors
  • HTTP 403 errors
  • Basic OAuth concepts
  • Protecting API credentials
  • Authentication in AI applications
KEY TAKEAWAY

Your API key or token is a secret credential.

The basic pattern is: store the credential securely → load it in Python → send it according to the API documentation → check the response. Never put real secrets directly into source code or commit them to Git.