AI Computer Institute
Expert-curated CS & AI curriculum aligned to CBSE standards. A bharath.ai initiative. About Us

API Auth

📚 Technology⏱️ 19 min read🎓 Grade 8
✍️ AI Computer Institute Editorial Team Updated: August 2026 CBSE-aligned · Peer-reviewed · 19 min read
Content curated by subject matter experts with IIT/NIT backgrounds. All chapters are fact-checked against official CBSE/NCERT syllabi.

Open the weather app on your phone. It shows "Bengaluru, 29°C, light rain" within a second of you tapping it. Your phone did not measure the temperature itself — it sent a message across the internet to a weather company's computer, asking "what's the weather in Bengaluru right now?", and got an answer back. That message-passing system, where one program asks another program for data or a service, is called an API — an Application Programming Interface.

Now ask a harder question. The IRCTC app knows which train seats you have booked, not which seats a stranger booked. Your school's attendance portal shows your class's attendance, not every class in the district. Somehow, when your app talks to the server, the server has to know who is asking before it decides what to tell them. That "who is asking, and are they allowed to ask this" check is called API authentication — API auth, for short. It is the single most important safety mechanism in every API you will ever use, and it is the subject of this chapter.

Why "Anyone Can Ask" Would Be a Disaster

Imagine your school library had no ID card system — anyone off the street could walk up to the counter and say "give me the register of every student's home address," and the librarian would just hand it over. That is exactly what an API with no authentication looks like. A server that answers every request from every stranger, with no way to check who is asking, cannot protect anyone's data and cannot stop anyone from hammering it with a million requests a second.

So real APIs demand proof of identity with every single request. That proof usually travels inside something called an HTTP header — a small labelled slip of information attached to the request, separate from the main content, the way a courier parcel has an address label stuck on the outside separate from what's packed inside. The most common header used for this purpose is literally named Authorization.

Method 1: The API Key

The simplest form of API auth is the API key — a long, unique, hard-to-guess string that a service hands you when you register as a developer. Every time your program calls the API, it attaches this key. The server keeps a list of every key it has ever issued and who it belongs to. If your key is on the list, the server trusts you and does the work; if it isn't, the server refuses.

Let's make this concrete. Suppose your school has built an internal Attendance API for teachers' apps to query. You've been issued the key aici_8f3e9d2b1a. Here is exactly how a teacher's app would call it in Python, using the popular requests library:

import requests

API_KEY = "aici_8f3e9d2b1a"
url = "https://api.school.in/attendance"

headers = {
    "Authorization": "Bearer " + API_KEY
}

response = requests.get(url, headers=headers)
print(response.status_code)
print(response.json())

Let's trace this line by line, because every line matters:

  • Line 1 imports the requests library, which knows how to build and send HTTP requests over the network.
  • Lines 3–4 store the key and the target address (URL) as plain Python strings. Nothing has been sent yet.
  • Lines 6–8 build a dictionary called headers with one entry. The value "Bearer " + API_KEY concatenates the word "Bearer", a space, and the key, producing the string "Bearer aici_8f3e9d2b1a". "Bearer" is a convention meaning "whoever presents (bears) this token is authorized" — you will see it in almost every modern API.
  • Line 10 is where the request actually leaves your computer. requests.get() sends a GET request to the URL, with the headers dictionary attached as real HTTP headers. The server receives both the URL and the header at the same time.
  • Line 11 prints response.status_code — a three-digit number the server sends back describing what happened.
  • Line 12 prints response.json(), which parses the server's reply (which arrived as text) back into a Python dictionary.

If the key is correct, the server's reply looks like this:

200
{'class': '8B', 'present': 38, 'total': 42}

Now watch what happens if a line in the code has a typo — say API_KEY = "aici_WRONG_KEY". Everything else in the program runs exactly the same way: the request is still built, still sent, still received by the server. But the server compares the string it receives against its list of valid keys, finds no match, and refuses to do the work:

401
{'error': 'Invalid API key'}

Notice something important: the program did not crash. Both times, requests.get() succeeded in the sense that it got a reply — the reply itself just carries bad news. This is a common misconception worth correcting explicitly: a "successful" network request and a "successful" authentication check are two completely different things. A beginner who only checks "did my code run without errors?" will miss authentication failures every time, because the failure is a normal HTTP response, not a program crash.

Here is roughly what the server is doing on its side, to make that comparison concrete rather than magical:

valid_keys = {"aici_8f3e9d2b1a": "Class 8B teacher account"}

def check_request(headers):
    auth_header = headers.get("Authorization", "")
    if not auth_header.startswith("Bearer "):
        return 401, {"error": "Missing or malformed Authorization header"}

    key = auth_header.replace("Bearer ", "")
    if key not in valid_keys:
        return 401, {"error": "Invalid API key"}

    return 200, {"class": "8B", "present": 38, "total": 42}

Trace it with the correct key: auth_header is "Bearer aici_8f3e9d2b1a", it does start with "Bearer ", so we strip that prefix and get key = "aici_8f3e9d2b1a". That string is a key in the valid_keys dictionary, so we skip both early-return statements and reach the final line: status 200, data returned. Trace it with the wrong key: the prefix check still passes (it still starts with "Bearer "), but key now equals "aici_WRONG_KEY", which is not in valid_keys — the second if catches it and returns 401 before the real attendance data is ever touched. The data is protected by a branch in the code, not by luck.

A Mistake You Will See Constantly: Keys in the URL

Some poorly designed (and some older) APIs accept the key as part of the URL instead of a header, like https://api.school.in/attendance?key=aici_8f3e9d2b1a. Resist this pattern whenever you have a choice. URLs get logged everywhere — in the browser's history, in the server's access logs, in any proxy sitting between you and the internet — while headers are generally treated as more sensitive and logged less often. A key sitting visibly in a URL is a key that will eventually leak into a screenshot, a shared link, or a log file someone forgets to secure. This is also why you must never commit an API key directly into code that you push to a public GitHub repository — it is one of the most common real-world security mistakes, and bots scan public repositories specifically looking for leaked keys within minutes of upload.

Method 2: Basic Authentication

Before the API-key convention became popular, and still in use in many systems today, is HTTP Basic Authentication: you send your username and password together, joined by a colon, then encoded using a scheme called Base64. For username rahul and password mySecret123, the raw text is rahul:mySecret123, and running it through Base64 encoding produces:

cmFodWw6bXlTZWNyZXQxMjM=

The request header then reads Authorization: Basic cmFodWw6bXlTZWNyZXQxMjM=. Here is the misconception to correct firmly: Base64 is not encryption — it is encoding, and it is trivially reversible by anyone who intercepts it. Encryption requires a secret key to undo; Base64 requires nothing but a standard, publicly known table (you can decode that string on any website's Base64 decoder tool right now and get back rahul:mySecret123). Base64 exists only to convert arbitrary bytes into safe-to-transmit text characters — it adds zero secrecy. This is precisely why Basic Auth is only ever safe to use over HTTPS, where a separate layer of real encryption (TLS) protects the entire message, header included, while it travels across the network.

Method 3: Bearer Tokens (and How They Differ from API Keys)

You already met the word "Bearer" in the API key example, so let's sharpen the distinction. An API key is usually a long-lived, unchanging string issued once when you register for a service — think of it like a laminated library membership card that stays valid for years. A token is usually issued fresh after you log in, and typically expires after a set time — an hour, a day — think of it like a same-day movie ticket stub. You show ID once at the box office (that's the login), and in exchange you get a stub (the token) that gets you through the door for today's show only. Tomorrow, that same stub is worthless; you need a new one.

Both travel the same way — inside an Authorization: Bearer ... header — which is why beginners often conflate them. The difference is entirely about how they were issued and how long they last, not about how they're transmitted.

Delegated Access: How "Sign in with Google" Actually Works

Here's a puzzle. When an app offers a "Sign in with Google" button, the app ends up able to show your Google profile photo and sometimes read your Google Drive files — yet the app never asks for your Google password. How can it access your account without ever knowing your password? The answer is a protocol called OAuth (short for Open Authorization), and it is the most important API-auth idea beyond simple keys.

The trick is that the app never talks to Google's servers with your password at all — you do, directly on Google's own login page, in a window Google controls. Once you approve, Google hands the app a token (not your password) that the app can use for a limited set of permissions. Walk through the numbered steps in the diagram below slowly; the order matters.

OAuth: How "Sign in with Google" Delegates Access Without Sharing a Password You (User) Homework App (the App) Google Login Page Google Drive API 1. You click "Sign in with Google" 2. App redirects your browser to Google's own page 3. You type your Google password directly into Google's page. The Homework App never sees it, sends it, or stores it. 4. Google gives the App a limited-time access token token: gho_a91f... (not your password) 5. App sends "Authorization: Bearer gho_a91f..." to Google Drive API Token accepted: App can now list your files Key idea: the App only ever holds a limited, revocable token — never your actual Google password. You can revoke that token any time from your Google account settings without changing your password.

Two details students often get backwards. First: the token the app receives is deliberately limited — when Google asked "allow Homework App to access your Drive files?", it was defining exactly what that token can and cannot do. A token issued for reading your profile name does not automatically let an app delete your files. Second: because the app never touches your password, you can revoke its access at any moment from your Google account's security settings, without changing your password at all — the token simply stops working the instant it's revoked, while every other app that logged in the same way keeps working normally.

Reading the Server's Reply: Status Codes That Actually Mean Something

You've already seen 200 and 401. Three status codes are essential to tell apart, and mixing up the last two is a very common mistake:

  • 200 OK — the request was authenticated and the server did the work.
  • 401 Unauthorized — the server does not know who you are: your key or token is missing, expired, or simply wrong. Fix: send valid credentials.
  • 403 Forbidden — the server knows exactly who you are (your credentials were accepted), but you are not allowed to do this particular thing. For example, a valid student-account token trying to access the "edit any student's marks" endpoint would get 403, not 401 — the identity check passed, the permission check failed.

This distinction between authentication (proving who you are — 401 territory) and authorization (deciding what you, specifically, are allowed to do — 403 territory) is one of the most confused pairs of words in this entire subject, precisely because they sound so similar. Authentication answers "who is this?" Authorization answers "is this person allowed to do that specific thing?" You always authenticate first and authorize second — the server cannot decide what you're permitted to do until it knows who you are.

Why All of This Falls Apart Without HTTPS

Every method above — API keys, Basic Auth, Bearer tokens — shares one absolute requirement: the connection itself must be encrypted, meaning the URL must start with https://, not http://. Here's why. Without encryption, your request travels across intermediate routers and networks as plain, readable text — like writing your password on a postcard instead of sealing it in an envelope. Anyone able to observe traffic on the same network (a classic risk on public Wi-Fi, for instance) can simply read the Authorization header straight out of the data as it passes by, no special skill required. HTTPS wraps the entire request — headers included — inside an encrypted tunnel called TLS, so an eavesdropper sees only scrambled bytes. This is precisely why Base64-encoded Basic Auth, which we showed above adds no real secrecy of its own, is considered acceptable only when HTTPS is doing the actual protective work underneath it.

Practice: Test Yourself

  1. A request is sent with the header Authorization: Bearer wrong_key_123 to the attendance API's check_request function shown earlier. Trace the function by hand: what status code and message come back, and which exact line of code produces it?
  2. Explain in one sentence why Base64-encoding a password inside a Basic Auth header does not, by itself, keep that password secret from someone reading network traffic.
  3. An app calls an endpoint with a perfectly valid, unexpired token — but the response is 403 Forbidden, not 401 Unauthorized. What does that tell you about the situation, and how is it different from a 401?
  4. A classmate suggests putting the API key directly into the URL, like ?apikey=aici_8f3e9d2b1a, "because it's simpler than headers." Give two concrete reasons this is a worse practice than sending the key in a header.
  5. In the OAuth diagram, at which numbered step does the Homework App come closest to ever seeing your actual Google password — and what is the actual answer to "does it ever see it"?

Answers: (1) The header does start with "Bearer " so the first if is skipped, but key becomes "wrong_key_123", which is not a key in valid_keys — the second if returns 401, {"error": "Invalid API key"}. (2) Base64 is a reversible, publicly documented encoding with no secret key needed to undo it — anyone intercepting the bytes can decode it back to plain text instantly. (3) A 403 means the server successfully identified who is making the request (authentication passed) but has decided that identity is not permitted to perform this particular action (authorization failed) — a 401 would mean the server couldn't even establish identity in the first place. (4) URLs get written into browser history and server access logs, and get accidentally shared whenever a link is copied or screenshotted, all of which leak the key; headers are far less commonly logged or displayed. (5) It never sees it at step 3 or any other step — you type your password only into Google's own page, and the App only ever receives the token handed over at step 4.

Summary

Every API that protects real data needs a way to know who is asking before it decides what to answer — that is API authentication. The API key is a long-lived identifier sent with each request, usually inside an Authorization header, and checked against a stored list on the server. Basic Authentication sends a username and password joined and Base64-encoded — remember that encoding is not encryption, so this only stays safe riding on top of HTTPS. Bearer tokens travel the same way as API keys but are typically short-lived and issued fresh after a login step, rather than handed out once and reused for years. OAuth lets one app get limited, revocable access to your account on another service (like Google) without that app ever seeing your actual password — you authenticate directly with the provider, and the app receives only a token. On the wire, 401 Unauthorized means the server couldn't verify who you are, while 403 Forbidden means it verified you but denied the specific action — authentication and authorization are two separate checks, always in that order. And underneath every one of these methods sits a non-negotiable requirement: the connection must be HTTPS, or the credentials are as exposed as writing them on a postcard.

← Data VizEnv Vars →

Found this useful? Share it!

📱 WhatsApp 🐦 Twitter 💼 LinkedIn