Lesson 2 — Beginner

The Web: HTTP, REST & JSON

Har AI feature ka aadha hissa bahar ke API se judna hota hai — LLM APIs se lekar internal services tak. Sab kuch HTTP par chalta hai. Is lesson mein request/response cycle, methods aur idempotency, status codes, headers/params/bodies, JSON handling, REST endpoint design, authentication basics aur curl se API inspect karna — sab practical examples ke saath dekhoge.

⏱ 30 min• Beginner• Python for AI Engineering

HTTP kya hai

WHAT

HTTP ek request-response protocol hai: client request bhejta hai (method + URL + headers + body), server response deta hai (status code + headers + body). Har website, mobile app aur API isi bhasha mein baat karti hai.

WHEN

Jab bhi tumhara code kisi doosre system se baat kare — LLM API, payment gateway, internal service, webhook — HTTP hi medium hai. Browser ke alawa background jobs bhi HTTP hi bhejte hain.

WHERE

Browser se lekar Python ke httpx client tak, CI pipelines, mobile apps, IoT devices — HTTP client har jagah hai. Jo URL tum roz kholte ho wo HTTP ka hi subset hai.

Ek line ka funda: HTTP stateless hai — har request apne aap mein poori hai, server ko yaad nahi rehta ki pichhli request kisne aayi thi. Isliye har request ke saath identity (token ya cookie) bhejni padti hai — authentication agle sections mein.

Yaad rakho: HTTP vs HTTPS: HTTPS matlab HTTP + TLS encryption. Production mein hamesha HTTPS — plain HTTP par headers (jismein token hota hai) kisi bhi proxy/logger mein chhapa rehta hai.

Request/response cycle — wire pe kya jaata hai

--- REQUEST (client se server) ---
POST /api/orders HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer eyJhbGciOi...

{"item": "gpu-hours", "qty": 2}

--- RESPONSE (server se client) ---
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/orders/981

{"id": 981, "status": "pending"}
Debug rule: Kisi API ka result samajh na aaye toh pehle poora exchange dekho — request ke headers/body aur response ke status/headers/body. Console ke messages nahi, wire pe kya gaya wahi matter karta hai.

Methods aur idempotency

GET    /orders        # padho — safe, repeat se kuch nahi badalta
POST   /orders        # naya banao — har call ek naya resource
PUT    /orders/981    # poora replace — do baar same result
PATCH  /orders/981    # thoda badlo (sirf given fields)
DELETE /orders/981    # hatao — doosri baar 404, lekin state same
Rule of thumb: Read = GET, create = POST, replace = PUT, partial edit = PATCH, remove = DELETE. Yehi verbs aur resources — REST ka poora khel yahin hai.

Status codes — families aur common codes

2xx  200 OK              201 Created (Location header ke saath)
     204 No Content       (delete success, body khaali)

4xx  400 Bad Request      client ne galat bheja (syntax/field)
     401 Unauthorized     login nahi hua (token do)
     403 Forbidden        login hai par permission nahi
     404 Not Found        resource hi nahi
     409 Conflict         state clash (duplicate, overlapping)
     422 Unprocessable    body parse hui par validation fail
     429 Too Many Requests  rate limit — thodi der baad try karo

5xx  500 Internal Server Error   server ka bug
     502/503/504                 upstream down/slow/missing
Trap: Client code mein sirf status_code == 200 check karna — 201/204 bhi success hain. Success ka matlab 2xx family, aur har non-2xx par explicit handling chahiye.

Headers, params aur bodies

# Query params — filter, sort, pagination
curl -sS "https://api.example.com/orders?status=pending&page=2" -H "Accept: application/json"

# Path params — resource ka identity: /orders/981
curl -sS "https://api.example.com/orders/981"

# Body + Content-Type — server ko batana zaroori hai andar kya hai
curl -sS -X POST "https://api.example.com/orders" -H "Content-Type: application/json" -d "{\"item\": \"gpu-hours\", \"qty\": 2}"
Practical note: curl example mein -d likhte waqt JSON ke quotes ko escape karna padta hai — isi liye teams -d @file.json ka use karti hain, file mein JSON rakh kar.

JSON ke saath confident kaam

import json

raw = "{\"id\": 981, \"qty\": 2, \"tags\": [\"rush\"]}"
order = json.loads(raw)             # string -> dict
order["qty"] += 1
text = json.dumps(order, indent=2)  # dict -> string

# Common traps
type(json.loads("1"))               # int — JSON number Python int/float banta hai
json.loads("None")                  # error — Python literal nahi, JSON hai
json.loads("{bad}")                 # error — pehle check karo ki body JSON hai
Yaad rakho: json module Python ka built-in hai — alag install karne ki zarurat nahi. API client likhna ho, data pipeline likhna ho, JSON har jagah isi se parse hota hai.

RESTful resource design

GET    /orders               # list (?status=, ?page=)
POST   /orders               # create            -> 201
GET    /orders/981           # one               -> 200 | 404
PATCH  /orders/981           # partial update    -> 200 | 409
DELETE /orders/981           # remove            -> 204 | 404

GET    /orders/981/items     # nested collection (lekin sirf 1 level tak)

# GALAT — verbs URLs mein
POST /getOrderById    GET /deleteOrder/981    /createNewOrder
Design rule: Pehle resources socho (kya-kya cheezein hain), phir har resource ke operations list karo. Status codes bhi design ka hissa hain — 409 clash kab aayega wo spec mein likho, baad mein yaad nahi aayega.

Authentication basics aur API debugging

# SAHI — secret header mein
curl -sS "https://api.example.com/me" -H "Authorization: Bearer $API_KEY"

# GALAT — secret URL mein (logs, browser history, proxies sab dekh lete hain)
curl -sS "https://api.example.com/me?api_key=sk-1234"

# Debug flags
curl -i -sS "https://api.example.com/orders/981"   # headers + body ek saath
curl -v -sS "https://api.example.com/orders/981"   # wire-level detail (TLS, redirect)
Rule: Secret ko code, URL aur repo se door rakho. Leak ho jaye toh turant rotate karo — revocation nahi, rotate. Authentication ka poora depth (OAuth flows, refresh tokens) baad ke levels mein, yahan sirf habits baith rahi hain.

Exercise

Question: Naya resource successfully banne par server commonly kaunsa status code return karta hai?

Question: Idempotent method kaunsa hai — POST ya PUT?

Question: Browser ke alawa API inspect/test karne ke liye is lesson ka standard CLI tool ka naam?

Question: JSON string ko Python dict banane wala function ka naam? (json module se)

Common mistakes

Desi example: Dakia aur parcel — HTTP ka desi cycle

Tum dakia ho: tumhare paas slip hai (method + address), ghar wala jawab deta hai (status + parcel). Slip galat toh parcel nahi milega (4xx), ghar hi band ho toh 5xx. Slip theek thi par nahi mila — garbar address mein hai:

text
REQUEST   : GET /orders/981 + headers        (Client -> Server)
SERVER    : routing -> order dhoondo -> (na mila toh status decide)
RESPONSE  : 404 Not Found + {"error": "not found"}  (Server -> Client)

Jo kuch curl se dekhte ho wahi browser bhi karta hai — fark sirf automation ka hai.
Interview angle — yahan se sawaal aate hain
  • Q: 401 aur 403 mein farq kya hai? — 401 authentication missing/invalid, 403 authorization nahi hai.
  • Q: Idempotency kyun matter karti hai retry ke context mein? — duplicate side effects bachane ke liye (PUT/DELETE safe, POST dangerous).
  • Q: GET aur POST ka practical farq ek order system mein? — GET data padhta hai (safe), POST naya resource banata hai (non-idempotent).
  • Q: API secrets header mein kyun, URL mein kyun nahi? — URLs logs/history/proxies mein jaate hain.
  • Q: 429 aaye toh client ko kya karna chahiye? — backoff ke saath retry, tight loop nahi.
Lesson complete?

HTTP ka base ready. Agla lesson — Building APIs with FastAPI — mein yahi concepts server ki taraf se banayenge: routes, validation, errors aur free docs.

Popular courses: Data Science Course in Lucknow · AI Course in Lucknow · Python Course in Lucknow · Power BI Course · Data Analytics Course