
FastAPI
API keys are the simplest way to secure API endpoints. They're static tokens that clients send with each request, ideal for server-to-server communication and simple integrations.
API keys authenticate requests without involving users:
from fastapi import FastAPI, HTTPException, Header
app = FastAPI()
API_KEY = "super-secret-key-12345"
@app.get("/data")
async def get_data(x_api_key: str = Header()):
if x_api_key != API_KEY:
raise HTTPException(status_code=401, detail="Invalid API key")
return {"data": "secret information"}Never hardcode keys in your application:
import os
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.getenv("API_KEY")
@app.get("/secure")
async def secure_endpoint(x_api_key: str = Header()):
if x_api_key != API_KEY:
raise HTTPException(status_code=401, detail="Invalid key")
return {"message": "authenticated"}from fastapi import Security, HTTPException
async def verify_api_key(api_key: str = Header()):
if api_key != API_KEY:
raise HTTPException(status_code=403, detail="Invalid API key")
return api_key
@app.get("/protected")
async def protected(key: str = Security(verify_api_key)):
return {"message": "access granted"}API keys are ideal for:
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward