Kyun Seekhna Zaroori Hai?

APIs se models ko accessible banate hain � mobile apps, web apps sab API se connect hote hain. Bina API ke, aapka AI model sirf ek script hai jo kisi ke computer pe chalti hai. API ke through aap apne model ko duniya ke saamne la sakte ho!

Prerequisite:

Ye lesson Python for AI ke baad seekhna best hai. Python basics aur HTTP concepts samajhna zaroori hai.

Core Concepts

REST

HTTP methods - GET, POST, PUT, DELETE. Ye APIs ke building blocks hain jo data exchange ke rules define karte hain.

ENDPOINTS

URLs jahan requests jaati hain. Jaise: /api/predict, /api/train - ye aapke model ke doors hain.

REQUEST/RESPONSE

Data flow pattern. Client request bhejta hai, server response deta hai. Ye API ka heartbeat hai.

AUTHENTICATION

API keys se security. Bina key ke koi bhi aapke model ko access nahi kar sakta - ye aapka digital lock hai.

Complete API Code Example

Ye ek complete FastAPI application hai jo sentiment analysis karti hai. Har line samajhte hain:

FastAPI - AI Model API
# Complete API with endpoints
from fastapi import FastAPI, HTTPException, Header
from pydantic import BaseModel
from typing import Optional

app = FastAPI(title="AI Model API")

# Models
class TextInput(BaseModel):
 text: str
 model: Optional[str] = "gpt-3.5"

class AnalysisResult(BaseModel):
 sentiment: str
 confidence: float
 keywords: list[str]

# API Key auth
API_KEY = "your-secret-key"

@app.post("/analyze", response_model=AnalysisResult)
async def analyze_text(input_data: TextInput, x_api_key: str = Header(...)):
 if x_api_key != API_KEY:
 raise HTTPException(status_code=401, detail="Invalid API key")
 
 # Simple analysis
 sentiment = "positive" if "good" in input_data.text.lower() else "neutral"
 return AnalysisResult(
 sentiment=sentiment,
 confidence=0.9,
 keywords=input_data.text.split()[:3]
 )

@app.get("/models")
async def list_models():
 return {"models": ["gpt-3.5", "gpt-4", "claude"]}
Test kaise karein:
POST request bhejo: http://localhost:8000/analyze
Header mein: X-API-Key: your-secret-key
Body: {"text": "This is good", "model": "gpt-3.5"}

Interactive Editor

Apna API code likho aur test karo:

Terminal ready. Run button dabao...

Exercise

Ye question aapko samajhna chahiye API development ke liye:

Question: REST API mein GET aur POST mein kya fark hai?

A: GET = data save karo, POST = data delete karo
B: GET = database connect karo, POST = file upload karo
C: GET = data nikalo, POST = data bhejo
D: GET = authentication karo, POST = logging karo