जब आप Python से किसी website, application, database service या online platform से data लेना चाहते हैं, तब हर बार उस system के internal code को directly access करना possible नहीं होता। इसके लिए एक standard communication method की जरूरत होती है। यही काम API करता है.
API का पूरा नाम Application Programming Interface है। Simple words में, API एक ऐसा interface है जिसके माध्यम से एक application दूसरे application या service से information या functionality request कर सकती है.
अगर आप Python में Data Analytics, automation या real-world projects करना चाहते हैं, तो API की basic understanding बहुत useful है। APIs की मदद से आप live या regularly updated data को programmatically access कर सकते हैं और फिर उस data को Python, Pandas या किसी analytics workflow में use कर सकते हैं.
मान लीजिए आप एक restaurant में गए हैं। आपके सामने kitchen है, लेकिन आप खुद kitchen में जाकर खाना बनाने या ingredients लेने नहीं जाते। आप waiter को अपनी request देते हैं। Waiter आपकी request kitchen तक पहुंचाता है और फिर तैयार खाना आपके पास वापस लाता है.
इस example में:
You
↓
Waiter
↓
Kitchen
↓
Waiter
↓
You
API को भी इसी तरह समझ सकते हैं:
Python Program
↓
API
↓
Server / Application
↓
API
↓
Python Program
Python application request भेजती है, API उस request को appropriate service तक पहुंचाने में मदद करता है, और फिर response वापस प्राप्त होता है.
API का primary purpose different software systems को एक controlled और defined तरीके से communicate करने देना है.
उदाहरण के लिए, एक application किसी API के माध्यम से:
ध्यान रखें कि हर API public नहीं होती। कुछ APIs public होती हैं, कुछ authentication मांगती हैं और कुछ केवल किसी organization के internal systems के लिए होती हैं.
Python का उपयोग केवल local files और calculations के लिए नहीं होता। Python external services से data प्राप्त करके उसे process और analyze भी कर सकता है.
एक basic workflow देखिए:
API
↓
Python
↓
Data
↓
Pandas
↓
Data Cleaning
↓
Analysis
↓
Visualization
यही कारण है कि APIs Data Analytics और Automation workflows में useful हैं.
उदाहरण के लिए, अगर कोई online service structured data API के माध्यम से provide करती है, तो Python उस data को request कर सकता है। उसके बाद उस data को Pandas DataFrame में convert करके आगे analysis किया जा सकता है.
API communication को समझने के लिए दो terms सबसे important हैं:
जब Python किसी API से information मांगता है, तो वह एक request भेजता है.
API request को process करने के बाद server एक response भेजता है.
Basic flow:
Python
|
| Request
↓
API / Server
|
| Response
↓
Python
यह communication internet के माध्यम से हो सकती है.
मान लीजिए किसी service के पास weather information है.
आपका Python program पूछता है:
"Delhi का current weather क्या है?"
Python API को request भेजता है.
Server request को process करता है और structured response भेज सकता है:
{
"city": "Delhi",
"temperature": 32,
"humidity": 65
}
अब Python इस information को read करके आगे process कर सकता है.
उदाहरण:
City: Delhi
Temperature: 32
Humidity: 65
यह सिर्फ conceptual example है। Actual API का response structure service के अनुसार अलग हो सकता है.
Website और API दोनों server से information provide कर सकते हैं, लेकिन उनका purpose और output अलग हो सकता है.
एक website सामान्यतः human users के लिए designed interface देती है.
API software applications के लिए structured communication interface provide करती है.
उदाहरण:
Human
↓
Website
↓
Visual Page
जबकि:
Python
↓
API
↓
Structured Data
API का response अक्सर JSON जैसे structured format में मिल सकता है, जिसे program आसानी से process कर सकता है.
API में एक important term है endpoint.
Endpoint वह specific URL या address होता है जहां application किसी particular API resource या functionality के लिए request भेज सकती है.
Conceptually:
https://example.com/api/users
यह एक hypothetical endpoint है.
अगर API users का data provide करती है, तो endpoint users resource को represent कर सकता है.
दूसरा endpoint हो सकता है:
https://example.com/api/products
यह products से संबंधित information provide कर सकता है.
इस प्रकार एक API के अंदर multiple endpoints हो सकते हैं.
API में resource उस type के data या object को represent कर सकता है जिसके साथ application काम करना चाहती है.
Examples:
users
products
orders
students
employees
weather
transactions
एक API अलग-अलग resources के लिए अलग endpoints provide कर सकती है.
उदाहरण:
/users
/products
/orders
इन paths को देखकर developer समझ सकता है कि API किस प्रकार के resource से संबंधित है.
अब complete communication को देखें:
Python Application
|
| HTTP Request
↓
API Endpoint
|
↓
Server
|
| HTTP Response
↓
Python Application
|
↓
Process Data
Python request भेजता है, server उसे process करता है और response वापस देता है.
इसके बाद Python response को read करके required data निकाल सकता है.
Web APIs के context में आपको HTTP term frequently दिखाई देगी.
HTTP का पूरा नाम Hypertext Transfer Protocol है। यह web पर client और server के बीच communication के लिए commonly used protocol है.
जब Python किसी web API को request भेजता है, तो वह अक्सर HTTP request के रूप में भेजी जाती है.
Basic structure:
Client
↓
HTTP Request
↓
Server
↓
HTTP Response
↓
Client
यहाँ Python program client की भूमिका निभा सकता है और API server की तरफ से response दे सकती है.
API concepts समझने के लिए client और server को समझना जरूरी है.
Client वह application या system है जो request करता है.
Server वह system है जो request receive करके appropriate response देता है.
Python program एक API interaction में client की तरह काम कर सकता है:
Python Program
↓
Client
↓
HTTP Request
↓
Server
Server response वापस भेजता है:
Server
↓
HTTP Response
↓
Python Program
एक HTTP API request में कई components हो सकते हैं। Basic level पर आपको इन concepts को समझना चाहिए:
हर request में सभी components जरूरी नहीं होते। यह API और operation पर depend करता है.
उदाहरण के लिए, data पढ़ने के लिए एक simple request केवल endpoint और appropriate method का उपयोग कर सकती है.
Server response में भी कई components हो सकते हैं:
Response body में actual requested data हो सकता है.
उदाहरण:
{
"name": "Rahul",
"marks": 85
}
यह JSON format में structured data का example है.
Web APIs में JSON बहुत common data format है.
JSON का पूरा नाम JavaScript Object Notation है। यह human-readable और machine-readable structured format है.
Example:
{
"name": "Rahul",
"age": 22,
"city": "Dehradun"
}
Python में JSON-like data अक्सर dictionary और list structures के साथ naturally work करता है.
Conceptually:
JSON Object
↓
Python Dictionary
JSON Array
↓
Python List
इसी कारण API से प्राप्त JSON data को Python में process करना relatively convenient होता है.
Data Analytics के लिए APIs का सबसे important use case external data को analysis workflow में लाना है.
उदाहरण:
API
↓
JSON
↓
Python
↓
Pandas DataFrame
↓
Data Cleaning
↓
Analysis
↓
Charts
मान लीजिए किसी API से daily sales data मिल रहा है। Python उस data को collect कर सकता है और Pandas में DataFrame बना सकता है.
फिर आप:
इस तरह API केवल programming concept नहीं है; यह real-world data collection का important source बन सकता है.
कुछ APIs freely accessible होती हैं, जबकि कुछ APIs request करने वाले application की identity verify करती हैं.
इस process को authentication कहा जाता है.
API authentication के लिए अलग-अलग mechanisms हो सकते हैं, जैसे:
इस lesson में आपको इनके detailed implementation की आवश्यकता नहीं है। अभी important concept यह समझना है कि कुछ APIs request स्वीकार करने से पहले credentials या token मांग सकती हैं.
उदाहरण के लिए, conceptual request में:
Authorization: Bearer TOKEN
जैसा header हो सकता है.
Actual authentication method हमेशा API documentation पर depend करेगा.
जब आप किसी API के साथ काम करते हैं, तो उसकी documentation सबसे important resources में से एक होती है.
Documentation आपको बताती है:
इसलिए API को guess करने की बजाय documentation पढ़ना एक important professional skill है.
कई APIs requests की संख्या पर limits लगाती हैं.
उदाहरण के लिए, कोई service एक समय period में केवल limited number of requests allow कर सकती है.
इसे rate limiting कहा जाता है.
इसका उद्देश्य server resources को protect करना और fair usage maintain करना हो सकता है.
इसलिए API-based Python programs बनाते समय unnecessary repeated requests करने से बचना चाहिए.
API interaction को इस simple flow से याद रखें:
1. Find API
↓
2. Read Documentation
↓
3. Identify Endpoint
↓
4. Send Request
↓
5. Receive Response
↓
6. Check Status
↓
7. Read JSON
↓
8. Process Data
आगे के lessons में हम इसी workflow को Python code के साथ implement करेंगे.
इस chapter में हमारा focus basic और practical API usage पर रहेगा। आपको मुख्य रूप से ये concepts सीखने होंगे:
requests library कैसे use करें?इस lesson का सबसे important concept यह है कि API software systems के बीच communication का एक interface provide करता है.
Python Application
↓
API
↓
Server
↓
Response
↓
Python
API request और response के माध्यम से applications data exchange कर सकती हैं। Web APIs में HTTP commonly used communication protocol है और JSON एक common response format है.
Data Analytics में API का practical workflow अक्सर इस प्रकार हो सकता है:
API
↓
JSON
↓
Python
↓
Pandas
↓
Data Cleaning
↓
Analysis
↓
Visualization
अब अगला important step है यह समझना कि HTTP request वास्तव में कैसे काम करती है, GET और POST methods में क्या difference है, status codes जैसे 200, 404 और 500 क्या बताते हैं, और Python से API request कैसे भेजी जाती है.
अब हम API की सबसे important practical foundation समझेंगे: HTTP request और HTTP response। जब Python किसी web API से data मांगता है, तो वह सामान्यतः HTTP protocol के माध्यम से server को request भेजता है और server response वापस देता है.
API के साथ काम करते समय आपको मुख्य रूप से HTTP methods, status codes, request और response structure समझना जरूरी है। आगे जब हम Python की requests library use करेंगे, तो यही concepts directly काम आएंगे.
जब आपका Python program किसी API server से information मांगता है या server पर data भेजता है, तो वह एक HTTP request भेज सकता है.
Basic communication:
Python Program
↓
HTTP Request
↓
API Server
Request में server को यह information दी जा सकती है कि application क्या करना चाहती है.
उदाहरण के लिए:
GET /users
इसका basic meaning हो सकता है:
“Users resource की information प्राप्त करें.”
Server request process करने के बाद HTTP response भेजता है.
API Server
↓
HTTP Response
↓
Python Program
Response में आम तौर पर status information और, जरूरत होने पर, requested data शामिल होता है.
उदाहरण:
{
"name": "Rahul",
"age": 22
}
इस response को Python program आगे process कर सकता है.
पूरे communication को इस तरह याद रखें:
Client
↓
Request
↓
Server
↓
Process Request
↓
Response
↓
Client
यहाँ Python application client की भूमिका निभा सकती है.
उदाहरण के लिए:
Python
↓
GET request
↓
Weather API
↓
Weather data
↓
Python
HTTP method server को request के intended operation के बारे में बताता है। API में सबसे commonly encountered methods हैं:
Basic Python API learning के लिए सबसे पहले GET और POST पर focus करना useful है.
GET request का उपयोग generally server से information retrieve करने के लिए किया जाता है.
उदाहरण:
GET /students
Conceptually इसका मतलब हो सकता है:
Give me the students data.
अगर API response JSON में data देती है:
{
"students": [
{
"name": "Rahul",
"marks": 85
},
{
"name": "Priya",
"marks": 92
}
]
}
Python इस response को read करके आगे analysis कर सकता है.
POST request का उपयोग generally server को data भेजने के लिए किया जाता है, अक्सर किसी resource को create करने या कोई server-side operation trigger करने के लिए.
उदाहरण:
POST /students
इसके साथ request body में data भेजा जा सकता है:
{
"name": "Amit",
"marks": 78
}
Server इस information को process करके response दे सकता है.
Conceptually:
Python
↓
POST + Data
↓
API Server
↓
Response
| Feature | GET | POST |
|---|---|---|
| Common purpose | Data retrieve करना | Data submit/create करना |
| Data location | अक्सर URL parameters में | अक्सर request body में |
| Typical use | Records पढ़ना | Data भेजना |
यह basic distinction है। Actual API behavior हमेशा उस API की documentation पर depend करता है.
API request में URL बहुत important है। URL यानी Uniform Resource Locator, server पर किसी resource या endpoint का address provide करता है.
उदाहरण:
https://example.com/api/students
इसे conceptually अलग parts में समझ सकते हैं:
https://
↓
Protocol
example.com
↓
Domain
/api/students
↓
API path / endpoint
Python API request में यह URL महत्वपूर्ण input होगा.
Endpoint API का वह specific location होता है जहाँ request भेजी जाती है.
उदाहरण:
https://example.com/api/students
यह students resource का endpoint हो सकता है.
दूसरा:
https://example.com/api/products
products का endpoint हो सकता है.
एक ही API के कई endpoints हो सकते हैं.
Server response में एक important component होता है HTTP status code.
Status code बताता है कि request का outcome broadly कैसा रहा.
कुछ common status codes:
200
201
400
401
403
404
500
इन codes को समझना API debugging के लिए बहुत important है.
200 OK generally बताता है कि request successfully process हुई.
उदाहरण:
Request
↓
API
↓
200 OK
↓
Data
अगर आपने GET request भेजी और response में 200 मिला, तो यह generally successful response का संकेत है.
201 Created commonly तब मिलता है जब request के result में नया resource successfully create हुआ हो.
यह POST requests के साथ commonly associated है, लेकिन actual API behavior documentation पर depend करता है.
Conceptually:
POST
↓
Create Resource
↓
201 Created
400 Bad Request generally indicate करता है कि server request को invalid या malformed मान रहा है.
Possible reasons में हो सकते हैं:
उदाहरण:
Request
↓
Invalid Data
↓
400 Bad Request
Exact reason API response body या documentation में मिल सकता है.
401 Unauthorized generally authentication से संबंधित problem को indicate करता है.
उदाहरण के लिए:
यह हमेशा “permission denied” का exact synonym नहीं है; authentication और authorization अलग concepts हैं.
403 Forbidden generally बताता है कि server ने request को समझ लिया लेकिन access allow नहीं किया.
Conceptually:
Request
↓
Server understands request
↓
Access denied
↓
403 Forbidden
यह authentication के बाद भी हो सकता है अगर authenticated user या application को requested resource की permission नहीं है.
404 Not Found का मतलब generally यह है कि requested resource या endpoint नहीं मिला.
उदाहरण:
GET /students/999999
अगर ऐसा student resource मौजूद नहीं है, तो API 404 response दे सकती है.
गलत endpoint URL भी 404 का कारण हो सकता है.
500 Internal Server Error generally server-side problem को indicate करता है.
यह जरूरी नहीं कि आपके Python code में ही error हो। Server application request process करते समय internal error encounter कर सकती है.
Conceptually:
Python
↓
Valid Request
↓
Server
↓
Internal Problem
↓
500
Production APIs में ऐसे errors के लिए retry strategy या proper error handling की आवश्यकता हो सकती है.
Status codes को broadly categories में भी समझ सकते हैं:
| Range | General Meaning |
|---|---|
| 1xx | Informational |
| 2xx | Successful |
| 3xx | Redirection |
| 4xx | Client-side request issues |
| 5xx | Server-side errors |
API development में सबसे frequently encountered categories 2xx, 4xx और 5xx हैं.
कई APIs आपको URL में additional information भेजने देती हैं। इन्हें query parameters कहा जा सकता है.
उदाहरण:
https://example.com/api/students?class=10
यहाँ:
class=10
एक query parameter है.
Conceptually इसका मतलब हो सकता है:
Get students
where class = 10
एक से अधिक parameters भी हो सकते हैं:
https://example.com/api/students?class=10&city=Dehradun
यहाँ:
class=10
city=Dehradun
दो query parameters हैं.
जब हम आगे requests library सीखेंगे, तो query parameters को manually URL में जोड़ने के बजाय Python dictionary के रूप में भी pass कर सकते हैं.
Conceptually:
params = {
"class": 10,
"city": "Dehradun"
}
और Python library उस information को request के साथ भेज सकती है.
यह approach code को cleaner बनाती है और special characters को correctly handle करने में मदद कर सकती है.
HTTP headers request या response के बारे में additional information provide करते हैं.
Request में headers का उपयोग कई purposes के लिए हो सकता है, जैसे:
उदाहरण:
Authorization: Bearer TOKEN
या:
Content-Type: application/json
इनका exact उपयोग API documentation पर depend करता है.
कुछ HTTP requests में client server को data भेजता है। यह data request body में रखा जा सकता है.
उदाहरण:
{
"name": "Rahul",
"marks": 85
}
POST request के context में यह data server को भेजा जा सकता है.
Basic structure:
POST
↓
URL
↓
Headers
↓
Request Body
↓
Server
Request body client से server की तरफ जा सकती है.
Response body server से client की तरफ वापस आ सकती है.
Python
|
| Request Body
↓
Server
|
| Response Body
↓
Python
दोनों bodies में JSON data हो सकता है, लेकिन यह API और request type पर depend करता है.
जब Python API response receive करता है, तो आपको तीन basic चीजें check करने की habit develop करनी चाहिए:
उदाहरण:
Status:
200
Response:
{
"city": "Dehradun",
"temperature": 25
}
यह देखकर आप समझ सकते हैं कि request successful रही और response में structured data मिला.
API हमेशा successful response नहीं देगी। Network problems, invalid parameters, authentication issues या server problems हो सकते हैं.
इसलिए Python program में केवल यह assume करना अच्छा practice नहीं है कि:
Request → Always Success
बल्कि:
Request
↓
Check Response
↓
Success?
┌───────┴───────┐
Yes No
↓ ↓
Process Handle Error
Data
यह approach reliable API programs बनाने के लिए important है.
| Concept | Basic Purpose |
|---|---|
| GET | Data retrieve करना |
| POST | Data submit/create करना |
| PUT | Resource को update/replace करना |
| PATCH | Resource के हिस्से को update करना |
| DELETE | Resource delete करना |
| 200 | Successful request |
| 201 | Resource created |
| 400 | Bad request |
| 401 | Authentication issue |
| 403 | Access forbidden |
| 404 | Resource/endpoint not found |
| 500 | Server-side error |
API communication को एक conversation की तरह सोचिए:
Python:
"मुझे students का data चाहिए."
↓
API:
"यह रहा आपका response."
↓
Python:
"Status 200 है, data मिल गया."
↓
Python:
"अब मैं इसे analyze करूंगा."
अगर problem हो:
Python
↓
Request
↓
API
↓
404 / 401 / 400 / 500
↓
Python handles the problem
यही basic foundation आगे Python की requests library में दिखाई देगी.
इस lesson के बाद आपको इन concepts को clearly समझना चाहिए:
अब हमारे पास API communication की foundation है। अगला practical step है Python की requests library का उपयोग करके वास्तविक HTTP requests भेजना, response प्राप्त करना और JSON data को Python में पढ़ना.
अब हम API के theoretical concepts को Python code में implement करना शुरू करेंगे। इसके लिए Python में सबसे commonly used libraries में से एक है requests। इसका उपयोग HTTP requests भेजने और API responses प्राप्त करने के लिए किया जाता है.
इस lesson में हम सीखेंगे कि Python से API को GET request कैसे भेजें, response कैसे देखें, status code कैसे check करें और JSON data को Python objects में कैसे convert करें.
requests एक Python library है जो HTTP requests को simple तरीके से भेजने में मदद करती है.
API के साथ काम करने के लिए आपको low-level networking details manually handle करने की जरूरत नहीं पड़ती। आप relatively simple Python syntax से request भेज सकते हैं.
Basic example:
import requests
response = requests.get(
"https://example.com"
)
print(response.status_code)
यहाँ:
import requests library को import करता है.requests.get() GET request भेजता है.response में server का response store होता है.response.status_code HTTP status code देता है.अगर आपके Python environment में requests available नहीं है, तो इसे pip के माध्यम से install किया जा सकता है:
pip install requests
अगर आप Anaconda environment use कर रहे हैं, तो अपने active environment में package उपलब्ध होना सुनिश्चित करें.
Installation के बाद test करें:
import requests
print("Requests is ready")
अगर कोई import error नहीं आता, तो library successfully available है.
अब एक simple GET request भेजते हैं:
import requests
url = "https://example.com"
response = requests.get(url)
print(response.status_code)
अगर server successful response देता है, तो status code generally 200 हो सकता है.
लेकिन हमेशा यह assume नहीं करना चाहिए कि response successful होगा। इसलिए status code check करना अच्छी practice है.
requests.get() केवल raw text return नहीं करता। यह एक Response object देता है.
उदाहरण:
response = requests.get(url)
इस object में response से संबंधित कई useful properties और methods हो सकते हैं.
सबसे common हैं:
response.status_code
response.text
response.json()
response.headers
इनका उपयोग अलग-अलग information प्राप्त करने के लिए किया जाता है.
Status code check करने के लिए:
print(response.status_code)
उदाहरण:
if response.status_code == 200:
print("Request successful")
else:
print("Request failed")
यह basic error checking का पहला step है.
response.text response body को text के रूप में access करने देता है.
print(response.text)
अगर server HTML या plain text return करता है, तो यह useful हो सकता है.
API के context में भी response text को debugging के लिए देखना useful हो सकता है.
उदाहरण:
print(
response.text[:500]
)
यह response के शुरुआती 500 characters देखने में मदद कर सकता है.
अगर API response JSON format में है, तो response.json() उसका parsed Python representation देने में मदद करता है.
उदाहरण:
data = response.json()
print(data)
अगर JSON object है, तो Python में वह अक्सर dictionary की तरह दिखाई देगा.
उदाहरण response:
{
"name": "Rahul",
"age": 22,
"city": "Dehradun"
}
Python में:
data = response.json()
print(data["name"])
print(data["age"])
Output conceptually होगा:
Rahul
22
API response हमेशा एक single object नहीं होता। कई APIs records की list return करती हैं.
उदाहरण:
[
{
"name": "Rahul",
"marks": 85
},
{
"name": "Priya",
"marks": 92
},
{
"name": "Amit",
"marks": 78
}
]
जब आप:
data = response.json()
करते हैं, तो यह Python list के रूप में process की जा सकती है.
फिर:
for student in data:
print(
student["name"],
student["marks"]
)
जैसा code use किया जा सकता है.
एक अच्छी habit है कि response successful है या नहीं, यह check करने के बाद data process करें.
import requests
url = "https://example.com/api/data"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print(data)
else:
print(
"Request failed:",
response.status_code
)
इससे program failure को gracefully handle करने की दिशा में पहला step लेता है.
requests library में raise_for_status() method भी उपलब्ध है.
उदाहरण:
response = requests.get(url)
response.raise_for_status()
data = response.json()
यह method unsuccessful HTTP status responses के लिए exception raise कर सकता है.
इसका फायदा यह है कि आपको हर status code को manually compare करने की जरूरत कुछ situations में नहीं पड़ती.
API requests network-related problems encounter कर सकती हैं। इसलिए exception handling useful है.
import requests
url = "https://example.com/api/data"
try:
response = requests.get(
url,
timeout=10
)
response.raise_for_status()
data = response.json()
print(data)
except requests.RequestException as error:
print(
"API request failed:",
error
)
यहाँ requests.RequestException requests-related exceptions को handle करने के लिए useful base exception है.
Network request में server response आने में समय लग सकता है। अगर आप timeout specify नहीं करते, तो कुछ situations में program unnecessarily लंबे समय तक wait कर सकता है.
इसलिए:
response = requests.get(
url,
timeout=10
)
जैसा timeout specify करना practical programs में useful है.
यहाँ 10 seconds एक example value है। Actual timeout application की requirements और API behavior के अनुसार तय किया जा सकता है.
अब मान लीजिए API को URL में filters या search parameters चाहिए.
Manual URL:
https://example.com/api/students?class=10&city=Dehradun
इसे Python में parameters dictionary के साथ लिखा जा सकता है:
import requests
url = "https://example.com/api/students"
params = {
"class": 10,
"city": "Dehradun"
}
response = requests.get(
url,
params=params
)
यह approach readable और maintainable है.
आप final URL को inspect भी कर सकते हैं:
print(response.url)
यह debugging के दौरान useful हो सकता है.
मान लीजिए आपको ये filters भेजने हैं:
category = "electronics"
page = 2
limit = 20
आप लिख सकते हैं:
params = {
"category": "electronics",
"page": 2,
"limit": 20
}
response = requests.get(
url,
params=params
)
इससे request के parameters clearly अलग दिखाई देते हैं.
API request में headers भी भेजे जा सकते हैं.
उदाहरण:
headers = {
"Accept": "application/json"
}
response = requests.get(
url,
headers=headers
)
अगर API authentication मांगती है, तो documentation के अनुसार authorization header भी भेजा जा सकता है.
उदाहरण:
headers = {
"Authorization": "Bearer YOUR_TOKEN"
}
Important: Real API tokens या secret keys को public code, screenshots, Git repositories या social media posts में expose नहीं करना चाहिए.
कुछ APIs API key मांगती हैं। API documentation आपको बताएगी कि key कहाँ भेजनी है.
यह query parameter के रूप में हो सकता है:
params = {
"api_key": "YOUR_API_KEY"
}
या header में:
headers = {
"X-API-Key": "YOUR_API_KEY"
}
Exact parameter या header name API provider पर depend करता है.
अब दोनों concepts combine करें:
import requests
url = "https://example.com/api/data"
params = {
"page": 1,
"limit": 10
}
headers = {
"Accept": "application/json"
}
response = requests.get(
url,
params=params,
headers=headers,
timeout=10
)
response.raise_for_status()
data = response.json()
print(data)
यह एक basic but realistic API request pattern है.
अब तक का पूरा workflow:
Import requests
↓
Define API URL
↓
Add parameters
↓
Add headers if required
↓
Send GET request
↓
Set timeout
↓
Check response
↓
Read JSON
↓
Process data
यह pattern आप कई API-based Python projects में देखेंगे.
Real APIs में JSON structure simple नहीं भी हो सकता। Data nested हो सकता है.
उदाहरण:
{
"status": "success",
"data": {
"student": {
"name": "Rahul",
"marks": 85
}
}
}
Python में nested values access करने के लिए:
data = response.json()
name = data["data"]["student"]["name"]
marks = data["data"]["student"]["marks"]
print(name)
print(marks)
API documentation पढ़ते समय response structure को carefully समझना इसलिए important है.
अगर आप directly:
data["name"]
use करते हैं और name मौजूद नहीं है, तो KeyError आ सकता है.
कुछ situations में get() useful हो सकता है:
name = data.get(
"name",
"Unknown"
)
अगर name key मौजूद नहीं है, तो default value "Unknown" मिल सकती है.
जब आप किसी unfamiliar API के साथ पहली बार काम कर रहे हों, तो response को inspect करना useful है.
print(
response.status_code
)
print(
response.headers
)
print(
response.text
)
अगर response JSON है:
print(
response.json()
)
इससे आपको actual response structure समझने में मदद मिलती है.
Wrong URL:
requests.get(
"wrong-url"
)
Endpoint को API documentation से verify करें.
Missing parameters:
अगर API required parameter मांगती है और आपने नहीं भेजा, तो error response मिल सकता है.
Wrong authentication:
Invalid या missing API key/token से authentication-related error आ सकता है.
No timeout:
Network programs में timeout specify करना अक्सर बेहतर practice है.
Ignoring status codes:
हर response को successful मानकर response.json() करना हमेशा appropriate नहीं है.
एक Python file बनाइए:
api_test.py
इसमें:
requests import करें.आपका basic structure ऐसा हो सकता है:
import requests
url = "API_URL"
try:
response = requests.get(
url,
timeout=10
)
response.raise_for_status()
data = response.json()
print(data)
except requests.RequestException as error:
print(
"Request failed:",
error
)
requests Python में HTTP requests भेजने के लिए widely used library है.requests.get() GET request भेजता है.response.status_code HTTP status code देता है.response.json() JSON response को Python data structure में parse करने में मदद करता है.params के माध्यम से query parameters भेजे जा सकते हैं.headers के माध्यम से additional request information भेजी जा सकती है.timeout network requests को indefinitely wait करने से बचाने में मदद करता है.raise_for_status() unsuccessful HTTP responses के लिए exception raise कर सकता है.try/except के माध्यम से request-related errors handle किए जा सकते हैं.अब आप Python से API request भेजने और response पढ़ने की basic प्रक्रिया समझ चुके हैं। अगला step है API endpoints, parameters, headers और JSON responses को एक practical API example के साथ deeply समझना, और फिर API data को Pandas DataFrame में convert करना.
अब तक आपने समझा कि API क्या है, HTTP request कैसे काम करती है और Python की requests library से GET request कैसे भेजी जाती है। अब हम API request के उन components को detail में समझेंगे जिनका practical Python projects में बार-बार उपयोग होता है—API endpoints, query parameters, headers और JSON data.
इन concepts को समझना इसलिए important है क्योंकि real-world APIs अक्सर केवल एक URL पर simple request स्वीकार नहीं करतीं। आपको यह बताना पड़ सकता है कि कौन-सा data चाहिए, कौन-सा page चाहिए, किस format में response चाहिए और authentication कैसे करनी है.
API endpoint वह specific URL होता है जहाँ application किसी particular resource या operation के लिए request भेजती है.
उदाहरण:
https://example.com/api/students
यह एक hypothetical students endpoint है.
अगर इसी API में individual student को ID से access करना हो, तो endpoint कुछ ऐसा हो सकता है:
https://example.com/api/students/101
यहाँ 101 student की identifier हो सकती है.
Conceptually:
/students
↓
All students
/students/101
↓
Student with ID 101
Actual endpoint structure हमेशा API documentation पर depend करता है.
कई APIs में एक base URL होता है जिसके बाद अलग-अलग endpoint paths आते हैं.
उदाहरण:
Base URL:
https://example.com/api
Endpoints:
/students
/products
/orders
Combined URLs:
https://example.com/api/students
https://example.com/api/products
https://example.com/api/orders
यह structure API documentation को समझने में useful है.
कई बार आपको पूरे resource का data नहीं चाहिए। आपको किसी specific condition के आधार पर data चाहिए। ऐसे cases में query parameters उपयोग किए जा सकते हैं.
उदाहरण:
https://example.com/api/students?class=10
यहाँ:
class=10
query parameter है.
इसका conceptual meaning हो सकता है:
Return students
whose class is 10.
एक request में multiple parameters भेजे जा सकते हैं.
https://example.com/api/students?class=10&city=Dehradun
इसमें दो parameters हैं:
class=10
city=Dehradun
Python में इन्हें manually URL string में जोड़ने के बजाय dictionary के रूप में देना बेहतर और cleaner approach हो सकता है.
import requests
url = "https://example.com/api/students"
params = {
"class": 10,
"city": "Dehradun"
}
response = requests.get(
url,
params=params,
timeout=10
)
print(response.url)
requests library parameters को URL के साथ appropriately encode कर सकती है.
Beginner अक्सर ऐसा करते हैं:
url = (
"https://example.com/api/students"
"?class=10&city=Dehradun"
)
छोटे examples में यह काम कर सकता है, लेकिन parameters बढ़ने पर URL manually construct करना difficult और error-prone हो सकता है.
इसलिए:
params = {
"class": 10,
"city": "Dehradun"
}
जैसी approach अधिक readable है.
Large APIs अक्सर एक ही response में हजारों records नहीं भेजतीं। Data को multiple pages में divide किया जा सकता है। इसे pagination कहा जाता है.
उदाहरण:
page = 1
limit = 20
Python में:
params = {
"page": 1,
"limit": 20
}
response = requests.get(
url,
params=params,
timeout=10
)
कुछ APIs page और limit की बजाय अलग parameter names use करती हैं, जैसे offset, size या अन्य names. इसलिए documentation check करना जरूरी है.
API आपको filters भी provide कर सकती है.
उदाहरण:
params = {
"department": "sales",
"status": "active"
}
Server इन parameters के आधार पर filtered data return कर सकता है.
लेकिन filter names और उनके accepted values API-specific होते हैं.
HTTP headers request या response के बारे में additional information provide करते हैं.
Python में headers dictionary के रूप में दिए जा सकते हैं:
headers = {
"Accept": "application/json"
}
और request:
response = requests.get(
url,
headers=headers,
timeout=10
)
यहाँ Accept header client की preferred response format के बारे में information दे सकता है.
Accept header server को यह बताने के लिए उपयोग हो सकता है कि client किस प्रकार का response प्राप्त करना चाहता है.
उदाहरण:
headers = {
"Accept": "application/json"
}
यह API के लिए JSON response preference indicate कर सकता है.
हालांकि server का actual behavior API documentation और server configuration पर depend करता है.
Content-Type header request body के format को indicate कर सकता है.
अगर आप JSON data भेज रहे हैं, तो commonly:
Content-Type: application/json
का उपयोग किया जाता है.
यह concept POST या PUT जैसी requests में विशेष रूप से important होता है.
कुछ APIs authentication के लिए headers का उपयोग करती हैं.
एक common pattern है:
headers = {
"Authorization": "Bearer YOUR_TOKEN"
}
यहाँ YOUR_TOKEN केवल placeholder है.
Actual API token को code में directly expose करने से बचना चाहिए.
Real projects में secret values को environment variables या appropriate secret-management methods में रखना बेहतर practice है.
कुछ APIs API key मांगती हैं.
API documentation के अनुसार key header में भेजी जा सकती है:
headers = {
"X-API-Key": "YOUR_API_KEY"
}
या कभी-कभी query parameter के रूप में:
params = {
"api_key": "YOUR_API_KEY"
}
कौन-सा तरीका use करना है, यह API provider define करता है.
अगर आपके पास real API key है, तो इसे इस तरह public code में रखना avoid करें:
api_key = "real-secret-key"
अगर यह code GitHub, website या किसी public platform पर चला जाए, तो key leak हो सकती है.
Beginner projects में भी यह habit develop करें कि:
YOUR_API_KEY
जैसे placeholder use करें और real credentials को सुरक्षित रखें.
API data के साथ काम करते समय JSON बहुत important format है.
JSON का पूरा नाम JavaScript Object Notation है। यह structured data represent करने का widely used format है.
Simple JSON object:
{
"name": "Rahul",
"age": 22,
"city": "Dehradun"
}
Python में यह structure dictionary जैसा दिखाई देता है.
data = {
"name": "Rahul",
"age": 22,
"city": "Dehradun"
}
Values access करने के लिए:
print(data["name"])
print(data["city"])
JSON में multiple records represent करने के लिए array का उपयोग हो सकता है.
[
{
"name": "Rahul",
"marks": 85
},
{
"name": "Priya",
"marks": 92
},
{
"name": "Amit",
"marks": 78
}
]
Python में यह list of dictionaries की तरह काम कर सकती है.
students = [
{
"name": "Rahul",
"marks": 85
},
{
"name": "Priya",
"marks": 92
},
{
"name": "Amit",
"marks": 78
}
]
फिर loop:
for student in students:
print(
student["name"],
student["marks"]
)
Real APIs में nested JSON बहुत common है.
उदाहरण:
{
"status": "success",
"data": {
"student": {
"name": "Rahul",
"marks": 85
}
}
}
Python में nested value:
data["data"]["student"]["name"]
से access की जा सकती है.
लेकिन deep nested structures के साथ careful रहना चाहिए क्योंकि कोई intermediate key missing हो सकती है.
अगर API JSON response देती है, तो requests का:
response.json()
method response को Python object में parse करने में मदद करता है.
उदाहरण:
import requests
response = requests.get(
url,
timeout=10
)
response.raise_for_status()
data = response.json()
print(data)
इसके बाद आप normal Python operations perform कर सकते हैं.
अगर response है:
{
"name": "Rahul",
"marks": 85,
"city": "Dehradun"
}
तो:
data = response.json()
name = data["name"]
marks = data["marks"]
print(name)
print(marks)
यह API data को Python variables में लाने का basic तरीका है.
अगर किसी key का मौजूद होना guaranteed नहीं है, तो dictionary get() method useful हो सकता है.
name = data.get(
"name",
"Unknown"
)
अगर name मौजूद है तो उसकी value मिलेगी। अगर नहीं है, तो "Unknown" default value मिलेगी.
अब इन सभी concepts को एक request में combine करें:
import requests
url = "https://example.com/api/students"
params = {
"class": 10,
"page": 1
}
headers = {
"Accept": "application/json"
}
try:
response = requests.get(
url,
params=params,
headers=headers,
timeout=10
)
response.raise_for_status()
data = response.json()
print(data)
except requests.RequestException as error:
print(
"Request failed:",
error
)
यहाँ पूरा flow है:
Endpoint
+
Parameters
+
Headers
↓
HTTP Request
↓
API Server
↓
HTTP Response
↓
JSON
↓
Python Data
मान लीजिए documentation में लिखा है:
GET /products
Parameters:
category
page
limit
Response:
JSON
Python implementation conceptually:
url = "https://example.com/api/products"
params = {
"category": "laptop",
"page": 1,
"limit": 20
}
response = requests.get(
url,
params=params,
timeout=10
)
response.raise_for_status()
products = response.json()
Documentation को पढ़कर code में translate करना API programming का बहुत important skill है.
कई APIs response को wrapper object के अंदर return करती हैं.
उदाहरण:
{
"status": "success",
"count": 3,
"results": [
{
"name": "Product A",
"price": 100
},
{
"name": "Product B",
"price": 200
},
{
"name": "Product C",
"price": 300
}
]
}
अगर हमें products चाहिए:
data = response.json()
products = data["results"]
फिर:
for product in products:
print(
product["name"],
product["price"]
)
यह pattern real APIs में frequently दिखाई दे सकता है.
अगर API सीधे list return करती है:
[
{"name": "A", "price": 100},
{"name": "B", "price": 200}
]
तो:
products = response.json()
के बाद products list होगी.
अगर API wrapper object देती है:
{
"results": [
...
]
}
तो आपको:
data = response.json()
products = data["results"]
जैसा access करना होगा.
सभी APIs एक जैसी नहीं होतीं.
एक API में authentication header हो सकता है, दूसरी API में query parameter। एक API में response key results हो सकती है, दूसरी में data.
इसलिए यह assume करना गलत है कि हर API का structure exactly same होगा.
Professional workflow:
Read Documentation
↓
Understand Endpoint
↓
Understand Parameters
↓
Understand Authentication
↓
Understand Response
↓
Write Python Code
अब किसी documentation-based public API का example लेकर following steps करें:
requests.get() use करें.response.raise_for_status() use करें.response.json() से response parse करें.एक छोटा Python program बनाइए जो किसी public API से data प्राप्त करे और उसे display करे.
Basic architecture:
api_collector.py
↓
API Endpoint
↓
GET Request
↓
JSON Response
↓
Python List/Dictionary
↓
Display Selected Data
इस project में अभी Pandas की आवश्यकता नहीं है। पहले API response को correctly obtain और understand करना सीखें.
Accept response format preference indicate कर सकता है.Content-Type request body के format को describe कर सकता है.response.json() JSON response को Python data में parse करने में मदद करता है.अब आपने API endpoint, parameters, headers और JSON response को समझ लिया है। अगले practical step में हम API से प्राप्त JSON data को Pandas DataFrame में convert करेंगे और देखेंगे कि API data को Data Analytics workflow में कैसे इस्तेमाल किया जाता है.
अब हम Working with APIs chapter का practical हिस्सा पूरा करेंगे। आपने API basics, HTTP methods, status codes, endpoints, parameters, headers और Python की requests library सीख ली है। अब इन सभी concepts को एक complete API to Pandas DataFrame workflow में combine करेंगे.
इस project का मुख्य उद्देश्य यह समझना है कि real-world में API से data लेकर उसे Python में कैसे process किया जाता है और फिर Data Analytics के लिए Pandas DataFrame में कैसे बदला जाता है.
एक typical API-based Data Analytics workflow इस तरह दिखाई दे सकता है:
API
↓
HTTP Request
↓
JSON Response
↓
Python Dictionary/List
↓
Pandas DataFrame
↓
Data Inspection
↓
Data Cleaning
↓
Data Analysis
↓
Visualization
यही workflow आपको आगे Data Analytics projects में बार-बार देखने को मिलेगा.
सबसे पहले required libraries import करें:
import requests
import pandas as pd
यहाँ:
requests API से HTTP request भेजने के लिए है.pandas API से प्राप्त structured data को DataFrame में analyze करने के लिए है.अब API endpoint को variable में रखें:
url = "https://example.com/api/products"
यह केवल example endpoint है। किसी real API project में आपको उस API की official documentation से actual endpoint लेना होगा.
अगर API parameters accept करती है, तो उन्हें dictionary में define किया जा सकता है:
params = {
"page": 1,
"limit": 20
}
फिर:
response = requests.get(
url,
params=params,
timeout=10
)
यह approach manually URL construct करने की तुलना में cleaner है.
API response को सीधे DataFrame में convert करने से पहले response status check करें:
response.raise_for_status()
अगर request unsuccessful है, तो exception raise हो सकती है.
आप status code भी inspect कर सकते हैं:
print(response.status_code)
Successful request के लिए अक्सर 2xx status code प्राप्त हो सकता है.
अब response को JSON में parse करें:
data = response.json()
print(data)
यहाँ data Python dictionary या list हो सकती है, depending on the API response structure.
उदाहरण:
[
{
"id": 1,
"name": "Laptop",
"price": 55000
},
{
"id": 2,
"name": "Monitor",
"price": 18000
}
]
यह response Python में list of dictionaries की तरह काम कर सकता है.
अगर API सीधे list of dictionaries return करती है, तो Pandas DataFrame बनाना simple है:
df = pd.DataFrame(data)
print(df)
Output conceptually:
id name price
0 1 Laptop 55000
1 2 Monitor 18000
अब API data Pandas DataFrame में आ चुका है.
यह बहुत important step है क्योंकि अब आप Pandas की powerful data analysis capabilities का उपयोग कर सकते हैं.
DataFrame बनने के बाद सबसे पहले data को inspect करें:
print(df.head())
head() DataFrame की शुरुआती rows देखने के लिए useful है.
इसके बाद:
print(df.shape)
shape rows और columns की संख्या बताता है.
Columns देखने के लिए:
print(df.columns)
Data types देखने के लिए:
print(df.dtypes)
यह API data को analyze करने से पहले basic data inspection का हिस्सा है.
API से आने वाले data में missing values हो सकती हैं.
इसलिए:
print(
df.isnull().sum()
)
का उपयोग किया जा सकता है.
यह प्रत्येक column में missing values की संख्या दिखा सकता है.
उदाहरण:
name 0
price 0
category 2
rating 1
इससे आपको पता चलता है कि आगे cleaning की आवश्यकता कहाँ है.
अब API data पर normal Pandas operations perform किए जा सकते हैं.
उदाहरण:
average_price = df["price"].mean()
print(average_price)
Maximum price:
max_price = df["price"].max()
print(max_price)
Minimum price:
min_price = df["price"].min()
print(min_price)
अब API से आया data actual analysis का हिस्सा बन गया है.
मान लीजिए DataFrame में price column है और आपको केवल ₹20,000 से अधिक वाले products चाहिए:
expensive_products = df[
df["price"] > 20000
]
print(expensive_products)
यह API से प्राप्त data को analytical question में convert करने का simple example है.
Products को price के आधार पर descending order में sort किया जा सकता है:
sorted_df = df.sort_values(
"price",
ascending=False
)
print(sorted_df)
अब सबसे expensive products ऊपर दिखाई देंगे.
Real-world APIs में एक common situation यह है कि response directly list नहीं होती.
उदाहरण:
{
"status": "success",
"count": 3,
"results": [
{
"name": "Laptop",
"price": 55000
},
{
"name": "Monitor",
"price": 18000
},
{
"name": "Keyboard",
"price": 2500
}
]
}
यहाँ:
data = response.json()
के बाद data एक dictionary होगी.
Actual records निकालने के लिए:
records = data["results"]
अब:
df = pd.DataFrame(records)
का उपयोग किया जा सकता है.
अगर JSON structure nested है, तो Pandas का json_normalize() useful हो सकता है.
उदाहरण:
data = [
{
"name": "Rahul",
"location": {
"city": "Dehradun",
"state": "Uttarakhand"
}
}
]
Simple DataFrame बनाने पर nested structure अलग handling मांग सकता है.
json_normalize() nested JSON को tabular format में flatten करने में मदद कर सकता है:
from pandas import json_normalize
df = json_normalize(data)
print(df)
Conceptually output columns हो सकती हैं:
name
location.city
location.state
यह API data को analytics-friendly table में बदलने के लिए useful technique है.
अब पूरा basic workflow एक जगह देखें:
import requests
import pandas as pd
url = "https://example.com/api/products"
params = {
"page": 1,
"limit": 20
}
try:
response = requests.get(
url,
params=params,
timeout=10
)
response.raise_for_status()
data = response.json()
df = pd.DataFrame(data)
print(
df.head()
)
print(
df.shape
)
print(
df.isnull().sum()
)
except requests.RequestException as error:
print(
"API request failed:",
error
)
यह एक reusable basic template है, लेकिन actual API के response structure के अनुसार pd.DataFrame(data) वाले हिस्से को बदलना पड़ सकता है.
मान लीजिए API से product data मिला:
data = [
{
"product": "Laptop",
"category": "Electronics",
"price": 55000
},
{
"product": "Monitor",
"category": "Electronics",
"price": 18000
},
{
"product": "Keyboard",
"category": "Accessories",
"price": 2500
},
{
"product": "Mouse",
"category": "Accessories",
"price": 1500
}
]
DataFrame:
df = pd.DataFrame(data)
Average price:
print(
df["price"].mean()
)
Highest priced product:
highest = df.loc[
df["price"].idxmax()
]
print(highest)
Category-wise average price:
category_average = (
df.groupby("category")["price"]
.mean()
)
print(category_average)
अब API data केवल collect नहीं हुआ बल्कि actual business analysis में convert हो गया.
DataFrame बनने के बाद आप Python visualization libraries का उपयोग भी कर सकते हैं.
उदाहरण:
import matplotlib.pyplot as plt
df.plot(
x="product",
y="price",
kind="bar"
)
plt.show()
इस प्रकार:
API
↓
JSON
↓
DataFrame
↓
Analysis
↓
Visualization
एक complete analytics workflow बन सकता है.
अगर आपको बार-बार APIs से data fetch करना है, तो reusable function बनाना बेहतर है.
import requests
def fetch_api_data(
url,
params=None,
headers=None
):
response = requests.get(
url,
params=params,
headers=headers,
timeout=10
)
response.raise_for_status()
return response.json()
अब:
data = fetch_api_data(
url,
params=params
)
इससे API request logic reusable हो जाता है.
आप एक दूसरा function भी बना सकते हैं:
import pandas as pd
def json_to_dataframe(data):
return pd.DataFrame(data)
फिर:
data = fetch_api_data(
url,
params=params
)
df = json_to_dataframe(
data
)
यह separation of responsibilities का अच्छा example है.
एक professional project में API fetching और analysis को एक ही function में भर देना हमेशा जरूरी नहीं है.
आप structure बना सकते हैं:
api_client.py
↓
fetch data
data_processing.py
↓
clean data
analysis.py
↓
calculate insights
visualization.py
↓
create charts
main.py
↓
run workflow
यह modular approach बड़े projects में maintainability improve कर सकती है.
एक important distinction समझिए.
API error:
401
404
500
Timeout
Connection Error
Data problem:
Missing values
Wrong data type
Duplicate records
Unexpected columns
Invalid values
API successfully data दे सकती है लेकिन data फिर भी cleaning मांग सकता है.
इसलिए:
Successful API Request
≠
Clean Data
यह Data Analytics में बहुत important concept है.
DataFrame बनने के बाद basic validation करें.
print(df.columns)
print(df.shape)
print(df.dtypes)
print(df.isnull().sum())
अगर expected column missing है:
required_columns = [
"product",
"price"
]
for column in required_columns:
if column not in df.columns:
raise ValueError(
f"Missing column: {column}"
)
यह approach API response structure बदलने पर unexpected errors को जल्दी identify करने में मदद कर सकती है.
अगर आप API से हजारों records collect कर रहे हैं, तो एक ही समय में बहुत सारी requests भेजना उचित नहीं हो सकता.
API documentation में rate limits check करें.
Large data collection के लिए pagination use करनी पड़ सकती है:
Page 1
↓
Page 2
↓
Page 3
↓
Page 4
↓
...
हर API pagination अलग तरीके से implement कर सकती है.
अब एक complete mini project का task करें.
Goal: API से product data प्राप्त करके basic analytics report बनाना.
आपको following steps perform करने हैं:
Final workflow:
API
↓
requests.get()
↓
response.raise_for_status()
↓
response.json()
↓
pd.DataFrame()
↓
Data Cleaning
↓
Analysis
↓
Visualization
अगर API authentication के लिए secret token use करती है, तो token को source code में hard-code करने से बचें.
Development में environment variables का उपयोग किया जा सकता है.
Conceptually:
API_KEY = environment_variable
और फिर:
headers = {
"Authorization":
f"Bearer {API_KEY}"
}
इससे secret को code से अलग रखना आसान हो सकता है.
अब Working with APIs chapter के सभी important concepts को एक बार revise करें.
| Concept | What You Learned |
|---|---|
| API | Applications के बीच communication interface |
| Endpoint | Specific API resource का address |
| GET | Data retrieve करना |
| POST | Data भेजना/create करना |
| Parameters | Request को customize/filter करना |
| Headers | Additional request information |
| JSON | Structured API data format |
| requests | Python HTTP requests library |
| status_code | Request result check करना |
| raise_for_status() | HTTP errors को exception के रूप में handle करना |
| response.json() | JSON response को Python data में parse करना |
| DataFrame | API data को tabular analysis format में लाना |
| json_normalize() | Nested JSON को tabular structure में flatten करना |
अगर आपको इस पूरे chapter से केवल एक practical workflow याद रखना हो, तो इसे याद रखें:
import requests
import pandas as pd
response = requests.get(
url,
params=params,
timeout=10
)
response.raise_for_status()
data = response.json()
df = pd.DataFrame(data)
print(df.head())
लेकिन याद रखें कि pd.DataFrame(data) हर API response पर directly काम नहीं करेगा। अगर JSON nested है या records किसी key के अंदर हैं, तो पहले सही data level identify करना होगा.
अब आप APIs को Python projects में integrate करने की foundation रखते हैं। इस knowledge का उपयोग करके आप आगे कई practical projects बना सकते हैं:
इन projects में basic pattern अक्सर यही रहेगा:
External API
↓
Python requests
↓
JSON
↓
Pandas
↓
Cleaning
↓
Analysis
↓
Visualization
Working with APIs chapter अब complete है. आपने API basics से लेकर HTTP requests, endpoints, parameters, headers, JSON, Python requests और API-to-Pandas DataFrame workflow तक के important concepts cover कर लिए हैं.
अब Python course में अगला छोटा chapter Python for Automation Basics रखा जा सकता है, जिसमें केवल basic और practical automation concepts होंगे—बिना advanced automation में जाने के.
अब हम Python course के अगले important chapter पर आते हैं: Python Automation Basics। Python की सबसे useful capabilities में से एक है repetitive और time-consuming tasks को automate करना.
Automation का simple मतलब है ऐसा Python program बनाना जो किसी task को बार-बार manually करने की बजाय automatically perform कर सके.
उदाहरण के लिए, अगर आपको हर दिन किसी folder में मौजूद files की list बनानी है, files को rename करना है, data को process करना है या एक report तैयार करनी है, तो Python इन tasks को automate करने में मदद कर सकता है.
मान लीजिए आपको हर दिन यह काम करना पड़ता है:
अगर यह काम रोज repeat होता है, तो Python से इसका automated workflow बनाया जा सकता है:
Python Script
↓
Find Files
↓
Process Files
↓
Move / Rename
↓
Generate Report
अब आपको हर बार manually वही steps perform करने की आवश्यकता कम हो जाती है.
Python automation के लिए popular है क्योंकि इसकी syntax relatively simple है और इसके ecosystem में files, folders, spreadsheets, web requests और data processing के लिए कई useful libraries उपलब्ध हैं.
Basic automation में आप Python का उपयोग कर सकते हैं:
किसी भी automation task को design करते समय पहले task को छोटे steps में divide करना useful है.
Manual Task
↓
Identify Repeated Steps
↓
Write Python Logic
↓
Test
↓
Automate
उदाहरण के लिए, अगर आपको हर दिन CSV files process करनी हैं:
Find CSV Files
↓
Read CSV
↓
Clean Data
↓
Calculate Results
↓
Save Report
Python इन सभी steps को एक program में combine कर सकता है.
मान लीजिए आपको किसी list के सभी numbers का square निकालना है.
numbers = [1, 2, 3, 4, 5]
squares = []
for number in numbers:
squares.append(
number ** 2
)
print(squares)
यह technically एक simple automation example है क्योंकि repeated calculation manually करने की बजाय loop automatically सभी values को process कर रहा है.
Automation हमेशा complicated नहीं होती। अक्सर छोटे repetitive tasks से ही इसकी शुरुआत होती है.
Python automation का एक बहुत practical use case files और folders के साथ काम करना है.
इसके लिए Python में pathlib module बहुत useful है.
उदाहरण:
from pathlib import Path
folder = Path("data")
for file in folder.iterdir():
print(file.name)
यह folder के अंदर मौजूद entries को inspect करने में मदद करता है.
मान लीजिए आपको केवल CSV files चाहिए:
from pathlib import Path
folder = Path("data")
csv_files = folder.glob(
"*.csv"
)
for file in csv_files:
print(file.name)
अब Python automatically folder में CSV files identify कर सकता है.
यह manual file searching की तुलना में useful हो सकता है जब files की संख्या बहुत अधिक हो.
Python से folders भी create किए जा सकते हैं.
from pathlib import Path
folder = Path("reports")
folder.mkdir(
exist_ok=True
)
exist_ok=True का उपयोग करने से folder पहले से मौजूद होने पर unnecessary error से बचा जा सकता है.
Files को एक folder से दूसरे folder में move करने के लिए Path.rename() या appropriate file operations का उपयोग किया जा सकता है.
उदाहरण:
from pathlib import Path
source = Path(
"data/report.csv"
)
destination = Path(
"reports/report.csv"
)
source.rename(
destination
)
Real projects में file existence और destination conditions को check करना जरूरी है.
मान लीजिए किसी folder में files हैं:
report1.txt
report2.txt
report3.txt
आप Python loop से उन्हें systematically rename कर सकते हैं.
from pathlib import Path
folder = Path("reports")
for index, file in enumerate(
folder.glob("*.txt"),
start=1
):
new_name = (
f"report_{index}.txt"
)
file.rename(
folder / new_name
)
यह example दिखाता है कि repetitive file management tasks को automate किया जा सकता है.
Python से text file read करना भी automation workflows का हिस्सा हो सकता है.
from pathlib import Path
file = Path(
"data/example.txt"
)
text = file.read_text(
encoding="utf-8"
)
print(text)
अब Python file content को automatically read करके आगे process कर सकता है.
Python processed information को file में save भी कर सकता है.
from pathlib import Path
report = Path(
"reports/summary.txt"
)
report.write_text(
"Daily report completed.",
encoding="utf-8"
)
इस तरह Python data processing के बाद automatically report file generate कर सकता है.
Data Analytics students के लिए CSV automation विशेष रूप से useful है.
मान लीजिए आपको daily CSV file process करनी है:
sales.csv
Pandas का उपयोग करके:
import pandas as pd
df = pd.read_csv(
"sales.csv"
)
print(df.head())
अब आप automated calculations कर सकते हैं:
total_sales = df["sales"].sum()
average_sales = df["sales"].mean()
print(total_sales)
print(average_sales)
फिर result को report में save किया जा सकता है.
अब एक more realistic workflow देखें:
Find CSV Files
↓
Read CSV with Pandas
↓
Clean Data
↓
Calculate Metrics
↓
Save Result
उदाहरण:
from pathlib import Path
import pandas as pd
input_folder = Path("data")
output_folder = Path("reports")
output_folder.mkdir(
exist_ok=True
)
for file in input_folder.glob(
"*.csv"
):
df = pd.read_csv(file)
total = df["sales"].sum()
print(
file.name,
total
)
अब Python folder में मौजूद सभी CSV files को automatically process कर सकता है.
आपने पिछले chapter में APIs सीखी हैं। अब APIs और automation को combine करना बहुत powerful हो सकता है.
उदाहरण:
Python
↓
API Request
↓
Get Data
↓
Process Data
↓
Save Report
एक basic example:
import requests
url = "https://example.com/api/data"
response = requests.get(
url,
timeout=10
)
response.raise_for_status()
data = response.json()
print(data)
अब इसी data को CSV, Excel या database में save किया जा सकता है.
Automation का उद्देश्य केवल task को automatically run करना नहीं है। एक अच्छा automation script errors को भी handle करता है.
उदाहरण:
from pathlib import Path
file = Path(
"data/report.csv"
)
if file.exists():
print(
"File found"
)
else:
print(
"File not found"
)
यह simple validation script को unnecessary failure से बचाने में मदद कर सकती है.
Automation scripts में unexpected errors आ सकते हैं। इसलिए try और except useful हैं.
try:
with open(
"data/report.txt",
"r",
encoding="utf-8"
) as file:
content = file.read()
except FileNotFoundError:
print(
"File not found."
)
इससे program error आने पर अचानक terminate होने की बजाय appropriate message दे सकता है.
एक important professional habit है कि किसी task को automate करने से पहले manual process को अच्छी तरह समझें.
पहले identify करें:
फिर Python solution design करें.
Data Analyst के लिए automation बहुत useful skill हो सकती है.
उदाहरण:
Daily Raw Data
↓
Python Script
↓
Data Cleaning
↓
KPI Calculation
↓
Excel / CSV Report
↓
Dashboard
इससे repetitive manual reporting work को कम किया जा सकता है.
एक beginner-friendly project बनाइए: Automatic CSV Report Generator.
Project structure:
automation_project/
│
├── data/
│ ├── sales1.csv
│ ├── sales2.csv
│ └── sales3.csv
│
├── reports/
│
└── main.py
main.py का basic workflow:
Find CSV files
↓
Read each CSV
↓
Calculate total sales
↓
Calculate average sales
↓
Create summary
↓
Save report
यह project आपको Python, Pandas, file handling और automation को एक साथ practice करने देगा.
pathlib files और folders के automation में useful है.अगले lesson में हम automation को और practical बनाएंगे—एक complete workflow के साथ जिसमें multiple files को automatically process करना, data combine करना और final report generate करना शामिल होगा.
अब हम Python Automation को एक practical Data Analytics workflow में use करेंगे। पिछले lesson में आपने automation की basic concept, pathlib, CSV files, Pandas और API automation समझी थी। अब हम इन concepts को combine करके ऐसा Python program बनाएंगे जो multiple files को automatically identify करे, process करे, combine करे और एक final report तैयार करे.
यह type का automation Data Analyst और MIS workflows में बहुत useful हो सकता है, क्योंकि कई organizations में daily या weekly reports अलग-अलग files में आती हैं और उन्हें manually combine करना पड़ता है.
मान लीजिए आपके पास हर दिन अलग CSV files आती हैं:
sales_january.csv
sales_february.csv
sales_march.csv
sales_april.csv
अगर आपको इन सभी files को manually खोलकर copy-paste करना पड़े, तो इसमें काफी time लग सकता है.
Python से workflow बनाया जा सकता है:
Find Files
↓
Read Files
↓
Combine Data
↓
Clean Data
↓
Calculate KPIs
↓
Generate Report
एक बार script properly तैयार हो जाए तो similar structure वाली नई files को automatically process किया जा सकता है.
सबसे पहले एक project folder बनाइए:
sales_automation/
│
├── data/
│ ├── sales_01.csv
│ ├── sales_02.csv
│ ├── sales_03.csv
│ └── sales_04.csv
│
├── reports/
│
└── main.py
यहाँ:
data folder में input files रहेंगी.reports folder में output reports save होंगी.main.py automation program होगा.सबसे पहले pathlib से data folder identify करें:
from pathlib import Path
data_folder = Path("data")
files = data_folder.glob(
"*.csv"
)
for file in files:
print(file.name)
अब Python automatically सभी CSV files identify कर सकता है.
अगर folder में:
sales_01.csv
sales_02.csv
sales_03.csv
हैं, तो loop इन files को automatically process कर सकता है.
कई situations में files की list को explicitly store करना useful हो सकता है:
files = list(
data_folder.glob("*.csv")
)
print(files)
अब आप number of files भी check कर सकते हैं:
print(
"Files found:",
len(files)
)
यह automation शुरू करने से पहले एक basic validation step हो सकता है.
अगर कोई CSV file नहीं मिलती, तो program को meaningful message देना चाहिए:
files = list(
data_folder.glob("*.csv")
)
if not files:
print(
"No CSV files found."
)
else:
print(
len(files),
"files found."
)
यह simple check automation को अधिक reliable बनाता है.
अब प्रत्येक CSV file को Pandas DataFrame में पढ़ें:
import pandas as pd
from pathlib import Path
data_folder = Path("data")
files = list(
data_folder.glob("*.csv")
)
dataframes = []
for file in files:
df = pd.read_csv(file)
dataframes.append(df)
अब dataframes list में सभी individual DataFrames मौजूद हैं.
अगर सभी files में समान columns हैं, तो Pandas concat() के माध्यम से उन्हें combine किया जा सकता है:
combined_df = pd.concat(
dataframes,
ignore_index=True
)
अब multiple files का data एक single DataFrame में आ गया है.
Conceptually:
File 1
↓
DataFrame 1
↓
File 2
↓
DataFrame 2
↓
File 3
↓
DataFrame 3
↓
pd.concat()
↓
Combined DataFrame
जब multiple DataFrames combine किए जाते हैं, तो original indexes repeat हो सकते हैं.
उदाहरण:
File 1:
0
1
2
File 2:
0
1
2
ignore_index=True के साथ Pandas नया continuous index बना सकता है:
0
1
2
3
4
5
यह combined dataset को cleaner बनाता है.
Files combine करने के बाद तुरंत analysis शुरू न करें। पहले data inspect करें:
print(
combined_df.head()
)
Rows और columns:
print(
combined_df.shape
)
Column names:
print(
combined_df.columns
)
Data types:
print(
combined_df.dtypes
)
यह आपको combined dataset की basic structure समझने में मदद करेगा.
अब missing values check करें:
print(
combined_df.isnull().sum()
)
मान लीजिए result है:
product 0
quantity 2
sales 1
region 0
इसका मतलब कुछ records में data missing है.
Automation script में data cleaning rules business requirement के अनुसार define किए जा सकते हैं.
Multiple files combine करते समय duplicate records आ सकते हैं.
Basic duplicate check:
print(
combined_df.duplicated().sum()
)
अगर duplicates remove करने हैं:
combined_df = (
combined_df
.drop_duplicates()
)
लेकिन duplicates को blindly remove नहीं करना चाहिए। पहले समझें कि duplicate वास्तव में error है या legitimate repeated transaction.
अब मान लीजिए हमारे DataFrame में columns हैं:
product
quantity
sales
region
Total sales:
total_sales = (
combined_df["sales"]
.sum()
)
Total quantity:
total_quantity = (
combined_df["quantity"]
.sum()
)
Average sales:
average_sales = (
combined_df["sales"]
.mean()
)
अब Python automatically important business metrics calculate कर सकता है.
Calculated KPIs को एक dictionary में organize किया जा सकता है:
summary = {
"Total Sales": total_sales,
"Total Quantity":
total_quantity,
"Average Sales":
average_sales
}
फिर:
for key, value in summary.items():
print(
key,
":",
value
)
यह report generation के लिए useful foundation है.
Summary को DataFrame में भी बदला जा सकता है:
summary_df = pd.DataFrame({
"Metric": [
"Total Sales",
"Total Quantity",
"Average Sales"
],
"Value": [
total_sales,
total_quantity,
average_sales
]
})
अब इसे CSV या Excel report में save किया जा सकता है.
Combined dataset को output folder में save करें:
output_folder = Path(
"reports"
)
output_folder.mkdir(
exist_ok=True
)
output_file = (
output_folder /
"combined_sales.csv"
)
combined_df.to_csv(
output_file,
index=False
)
अब Python automatically combined CSV report बना देगा.
Summary DataFrame को अलग file में save किया जा सकता है:
summary_file = (
output_folder /
"sales_summary.csv"
)
summary_df.to_csv(
summary_file,
index=False
)
इस तरह automation के बाद दो useful outputs मिल सकते हैं:
reports/
│
├── combined_sales.csv
└── sales_summary.csv
Repeated logic को function में रखना बेहतर है.
def create_summary(df):
total_sales = (
df["sales"].sum()
)
total_quantity = (
df["quantity"].sum()
)
average_sales = (
df["sales"].mean()
)
return {
"Total Sales":
total_sales,
"Total Quantity":
total_quantity,
"Average Sales":
average_sales
}
अब:
summary = create_summary(
combined_df
)
इससे program ज्यादा modular हो जाता है.
एक useful improvement यह है कि data में source file का नाम भी store करें.
dataframes = []
for file in files:
df = pd.read_csv(file)
df["source_file"] = (
file.name
)
dataframes.append(df)
अब combined DataFrame में source_file column भी होगा.
यह बाद में यह पता लगाने में useful हो सकता है कि कौन-सा record किस source file से आया.
Automation में एक खराब या corrupted file पूरी process को रोक सकती है। इसलिए file-level error handling useful हो सकती है.
dataframes = []
for file in files:
try:
df = pd.read_csv(file)
dataframes.append(df)
print(
"Processed:",
file.name
)
except Exception as error:
print(
"Failed:",
file.name,
error
)
इस approach में एक file fail होने पर बाकी files process हो सकती हैं, depending on your workflow requirements.
अब सभी major concepts को एक basic script में combine करें:
from pathlib import Path
import pandas as pd
data_folder = Path("data")
output_folder = Path("reports")
output_folder.mkdir(
exist_ok=True
)
files = list(
data_folder.glob("*.csv")
)
if not files:
print(
"No CSV files found."
)
raise SystemExit
dataframes = []
for file in files:
try:
df = pd.read_csv(file)
df["source_file"] = (
file.name
)
dataframes.append(df)
print(
"Processed:",
file.name
)
except Exception as error:
print(
"Failed:",
file.name,
error
)
if not dataframes:
print(
"No files could be processed."
)
raise SystemExit
combined_df = pd.concat(
dataframes,
ignore_index=True
)
print(
"\nRows:",
len(combined_df)
)
print(
"\nMissing Values:"
)
print(
combined_df.isnull().sum()
)
combined_file = (
output_folder /
"combined_sales.csv"
)
combined_df.to_csv(
combined_file,
index=False
)
print(
"\nCombined file saved:"
)
print(combined_file)
यह beginner-level लेकिन realistic automation script है.
अब इसमें KPI report भी add कर सकते हैं:
total_sales = (
combined_df["sales"]
.sum()
)
average_sales = (
combined_df["sales"]
.mean()
)
total_quantity = (
combined_df["quantity"]
.sum()
)
summary_df = pd.DataFrame({
"Metric": [
"Total Sales",
"Average Sales",
"Total Quantity"
],
"Value": [
total_sales,
average_sales,
total_quantity
]
})
summary_file = (
output_folder /
"sales_summary.csv"
)
summary_df.to_csv(
summary_file,
index=False
)
अब script केवल files combine नहीं कर रही बल्कि automated analytical report भी बना रही है.
Automation scripts में final status message helpful होता है:
print(
"\nAutomation completed successfully."
)
आप processed file count भी दिखा सकते हैं:
print(
"Files processed:",
len(dataframes)
)
इससे user को तुरंत पता चलता है कि process complete हुई या नहीं.
Start
↓
Find data folder
↓
Find CSV files
↓
Validate files
↓
Read each CSV
↓
Add source information
↓
Combine DataFrames
↓
Inspect data
↓
Calculate KPIs
↓
Save combined dataset
↓
Save summary report
↓
Completion message
↓
End
यह एक complete basic automation pipeline है.
Automation विशेष रूप से useful है जब:
अगर कोई task केवल एक बार करना है, तो complex automation बनाना हमेशा जरूरी नहीं है.
| Manual Process | Python Automation |
|---|---|
| Files manually search करना | Python files automatically find करता है |
| Files manually open करना | Pandas automatically read कर सकता है |
| Copy-paste करना | pd.concat() से combine करना |
| Calculations manually करना | Python automatically calculate करता है |
| Report manually बनाना | Python output files generate कर सकता है |
Automation का मतलब केवल code को छोटा करना नहीं है। इसका उद्देश्य एक repeatable, reliable और understandable workflow बनाना है.
एक अच्छा automation program:
अब इसी project को खुद extend करें.
Task 1: Region-wise total sales calculate करें.
region_sales = (
combined_df
.groupby("region")["sales"]
.sum()
)
print(region_sales)
Task 2: सबसे ज्यादा sales वाली region identify करें.
Task 3: Output को अलग CSV file में save करें.
Task 4: केवल current month की files process करने की logic बनाने की कोशिश करें.
Task 5: Automation में एक log file create करें जिसमें processed files के names लिखे जाएं.
pathlib files खोजने और manage करने में useful है.pd.read_csv() CSV files को DataFrame में read कर सकता है.pd.concat() multiple DataFrames combine करने के लिए useful है.अब आपने Python automation के basic और practical workflow को समझ लिया है—files ढूंढना, multiple CSV files पढ़ना, combine करना, analysis करना और report generate करना। अगले part में हम automation को finalize करेंगे और automation project, scheduling का basic idea, best practices और final revision देखेंगे.
अब हम Python course के अगले important chapter पर आते हैं: Python Automation Basics। Python की सबसे useful capabilities में से एक है repetitive और time-consuming tasks को automate करना.
Automation का simple मतलब है ऐसा Python program बनाना जो किसी task को बार-बार manually करने की बजाय automatically perform कर सके.
उदाहरण के लिए, अगर आपको हर दिन किसी folder में मौजूद files की list बनानी है, files को rename करना है, data को process करना है या एक report तैयार करनी है, तो Python इन tasks को automate करने में मदद कर सकता है.
मान लीजिए आपको हर दिन यह काम करना पड़ता है:
अगर यह काम रोज repeat होता है, तो Python से इसका automated workflow बनाया जा सकता है:
Python Script
↓
Find Files
↓
Process Files
↓
Move / Rename
↓
Generate Report
अब आपको हर बार manually वही steps perform करने की आवश्यकता कम हो जाती है.
Python automation के लिए popular है क्योंकि इसकी syntax relatively simple है और इसके ecosystem में files, folders, spreadsheets, web requests और data processing के लिए कई useful libraries उपलब्ध हैं.
Basic automation में आप Python का उपयोग कर सकते हैं:
किसी भी automation task को design करते समय पहले task को छोटे steps में divide करना useful है.
Manual Task
↓
Identify Repeated Steps
↓
Write Python Logic
↓
Test
↓
Automate
उदाहरण के लिए, अगर आपको हर दिन CSV files process करनी हैं:
Find CSV Files
↓
Read CSV
↓
Clean Data
↓
Calculate Results
↓
Save Report
Python इन सभी steps को एक program में combine कर सकता है.
मान लीजिए आपको किसी list के सभी numbers का square निकालना है.
numbers = [1, 2, 3, 4, 5]
squares = []
for number in numbers:
squares.append(
number ** 2
)
print(squares)
यह technically एक simple automation example है क्योंकि repeated calculation manually करने की बजाय loop automatically सभी values को process कर रहा है.
Automation हमेशा complicated नहीं होती। अक्सर छोटे repetitive tasks से ही इसकी शुरुआत होती है.
Python automation का एक बहुत practical use case files और folders के साथ काम करना है.
इसके लिए Python में pathlib module बहुत useful है.
उदाहरण:
from pathlib import Path
folder = Path("data")
for file in folder.iterdir():
print(file.name)
यह folder के अंदर मौजूद entries को inspect करने में मदद करता है.
मान लीजिए आपको केवल CSV files चाहिए:
from pathlib import Path
folder = Path("data")
csv_files = folder.glob(
"*.csv"
)
for file in csv_files:
print(file.name)
अब Python automatically folder में CSV files identify कर सकता है.
यह manual file searching की तुलना में useful हो सकता है जब files की संख्या बहुत अधिक हो.
Python से folders भी create किए जा सकते हैं.
from pathlib import Path
folder = Path("reports")
folder.mkdir(
exist_ok=True
)
exist_ok=True का उपयोग करने से folder पहले से मौजूद होने पर unnecessary error से बचा जा सकता है.
Files को एक folder से दूसरे folder में move करने के लिए Path.rename() या appropriate file operations का उपयोग किया जा सकता है.
उदाहरण:
from pathlib import Path
source = Path(
"data/report.csv"
)
destination = Path(
"reports/report.csv"
)
source.rename(
destination
)
Real projects में file existence और destination conditions को check करना जरूरी है.
मान लीजिए किसी folder में files हैं:
report1.txt
report2.txt
report3.txt
आप Python loop से उन्हें systematically rename कर सकते हैं.
from pathlib import Path
folder = Path("reports")
for index, file in enumerate(
folder.glob("*.txt"),
start=1
):
new_name = (
f"report_{index}.txt"
)
file.rename(
folder / new_name
)
यह example दिखाता है कि repetitive file management tasks को automate किया जा सकता है.
Python से text file read करना भी automation workflows का हिस्सा हो सकता है.
from pathlib import Path
file = Path(
"data/example.txt"
)
text = file.read_text(
encoding="utf-8"
)
print(text)
अब Python file content को automatically read करके आगे process कर सकता है.
Python processed information को file में save भी कर सकता है.
from pathlib import Path
report = Path(
"reports/summary.txt"
)
report.write_text(
"Daily report completed.",
encoding="utf-8"
)
इस तरह Python data processing के बाद automatically report file generate कर सकता है.
Data Analytics students के लिए CSV automation विशेष रूप से useful है.
मान लीजिए आपको daily CSV file process करनी है:
sales.csv
Pandas का उपयोग करके:
import pandas as pd
df = pd.read_csv(
"sales.csv"
)
print(df.head())
अब आप automated calculations कर सकते हैं:
total_sales = df["sales"].sum()
average_sales = df["sales"].mean()
print(total_sales)
print(average_sales)
फिर result को report में save किया जा सकता है.
अब एक more realistic workflow देखें:
Find CSV Files
↓
Read CSV with Pandas
↓
Clean Data
↓
Calculate Metrics
↓
Save Result
उदाहरण:
from pathlib import Path
import pandas as pd
input_folder = Path("data")
output_folder = Path("reports")
output_folder.mkdir(
exist_ok=True
)
for file in input_folder.glob(
"*.csv"
):
df = pd.read_csv(file)
total = df["sales"].sum()
print(
file.name,
total
)
अब Python folder में मौजूद सभी CSV files को automatically process कर सकता है.
आपने पिछले chapter में APIs सीखी हैं। अब APIs और automation को combine करना बहुत powerful हो सकता है.
उदाहरण:
Python
↓
API Request
↓
Get Data
↓
Process Data
↓
Save Report
एक basic example:
import requests
url = "https://example.com/api/data"
response = requests.get(
url,
timeout=10
)
response.raise_for_status()
data = response.json()
print(data)
अब इसी data को CSV, Excel या database में save किया जा सकता है.
Automation का उद्देश्य केवल task को automatically run करना नहीं है। एक अच्छा automation script errors को भी handle करता है.
उदाहरण:
from pathlib import Path
file = Path(
"data/report.csv"
)
if file.exists():
print(
"File found"
)
else:
print(
"File not found"
)
यह simple validation script को unnecessary failure से बचाने में मदद कर सकती है.
Automation scripts में unexpected errors आ सकते हैं। इसलिए try और except useful हैं.
try:
with open(
"data/report.txt",
"r",
encoding="utf-8"
) as file:
content = file.read()
except FileNotFoundError:
print(
"File not found."
)
इससे program error आने पर अचानक terminate होने की बजाय appropriate message दे सकता है.
एक important professional habit है कि किसी task को automate करने से पहले manual process को अच्छी तरह समझें.
पहले identify करें:
फिर Python solution design करें.
Data Analyst के लिए automation बहुत useful skill हो सकती है.
उदाहरण:
Daily Raw Data
↓
Python Script
↓
Data Cleaning
↓
KPI Calculation
↓
Excel / CSV Report
↓
Dashboard
इससे repetitive manual reporting work को कम किया जा सकता है.
एक beginner-friendly project बनाइए: Automatic CSV Report Generator.
Project structure:
automation_project/
│
├── data/
│ ├── sales1.csv
│ ├── sales2.csv
│ └── sales3.csv
│
├── reports/
│
└── main.py
main.py का basic workflow:
Find CSV files
↓
Read each CSV
↓
Calculate total sales
↓
Calculate average sales
↓
Create summary
↓
Save report
यह project आपको Python, Pandas, file handling और automation को एक साथ practice करने देगा.
pathlib files और folders के automation में useful है.अगले lesson में हम automation को और practical बनाएंगे—एक complete workflow के साथ जिसमें multiple files को automatically process करना, data combine करना और final report generate करना शामिल होगा.