{"id":102,"date":"2025-10-25T07:11:45","date_gmt":"2025-10-25T07:11:45","guid":{"rendered":"https:\/\/codetypingpro.com\/?p=102"},"modified":"2025-12-17T07:49:40","modified_gmt":"2025-12-17T07:49:40","slug":"lesson-27-api-requests-in-python","status":"publish","type":"post","link":"https:\/\/codetypingpro.com\/?p=102","title":{"rendered":"Lesson 27: API Requests in Python"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\"><\/h3>\n\n\n\n<h3 class=\"wp-block-heading\">\ud83c\udfaf <strong>Lesson Objective<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To learn how to <strong>interact with APIs<\/strong> using Python, send requests, handle responses, and work with data from external sources such as web services or third-party platforms.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\udde9 <strong>1. What Is an API?<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>API (Application Programming Interface)<\/strong> allows one program to communicate with another.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>APIs are commonly used to fetch data from <strong>web services<\/strong>, interact with <strong>databases<\/strong>, or control <strong>external applications<\/strong>.<\/li>\n\n\n\n<li><strong>HTTP methods<\/strong> are mostly used:\n<ul class=\"wp-block-list\">\n<li><code>GET<\/code> \u2192 Retrieve data<\/li>\n\n\n\n<li><code>POST<\/code> \u2192 Send data<\/li>\n\n\n\n<li><code>PUT<\/code> \u2192 Update data<\/li>\n\n\n\n<li><code>DELETE<\/code> \u2192 Delete data<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\u2699\ufe0f <strong>2. Python Requests Module<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>requests<\/code> module is the <strong>most popular library<\/strong> for working with HTTP APIs in Python.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">\u2705 Install if not already installed:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>pip install requests\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Import the module:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import requests\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udd39 <strong>3. Sending a GET Request<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>GET requests<\/strong> are used to retrieve data from a server.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import requests\n\nurl = \"https:\/\/jsonplaceholder.typicode.com\/posts\/1\"\nresponse = requests.get(url)\n\n# Check response status\nprint(\"Status Code:\", response.status_code)\n\n# Get JSON data\ndata = response.json()\nprint(data)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output Example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  \"userId\": 1,\n  \"id\": 1,\n  \"title\": \"sunt aut facere repellat provident occaecati\",\n  \"body\": \"quia et suscipit...\"\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udd39 <strong>4. Sending a POST Request<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>POST requests<\/strong> send data to the server.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>url = \"https:\/\/jsonplaceholder.typicode.com\/posts\"\npayload = {\n    \"title\": \"Python API\",\n    \"body\": \"This is a test post\",\n    \"userId\": 1\n}\n\nresponse = requests.post(url, json=payload)\nprint(\"Status Code:\", response.status_code)\nprint(response.json())\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output Example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  \"title\": \"Python API\",\n  \"body\": \"This is a test post\",\n  \"userId\": 1,\n  \"id\": 101\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udd39 <strong>5. Adding Headers<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Sometimes APIs require <strong>headers<\/strong> for authentication or content type.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>url = \"https:\/\/jsonplaceholder.typicode.com\/posts\"\nheaders = {\"Content-Type\": \"application\/json\"}\n\nresponse = requests.get(url, headers=headers)\nprint(response.json()&#91;0])\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udd39 <strong>6. Handling Query Parameters<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Many APIs accept <strong>query parameters<\/strong> to filter or sort data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>url = \"https:\/\/jsonplaceholder.typicode.com\/posts\"\nparams = {\"userId\": 1}\n\nresponse = requests.get(url, params=params)\nposts = response.json()\n\nfor post in posts:\n    print(f\"{post&#91;'id']}: {post&#91;'title']}\")\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udd39 <strong>7. Error Handling in API Requests<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Always handle errors like network failures or invalid responses.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try:\n    response = requests.get(\"https:\/\/jsonplaceholder.typicode.com\/posts\/1\")\n    response.raise_for_status()  # Raises HTTPError for bad responses\n    data = response.json()\n    print(data)\nexcept requests.exceptions.HTTPError as err:\n    print(\"HTTP error occurred:\", err)\nexcept requests.exceptions.ConnectionError as err:\n    print(\"Connection error occurred:\", err)\nexcept requests.exceptions.Timeout as err:\n    print(\"Request timed out:\", err)\nexcept requests.exceptions.RequestException as err:\n    print(\"An error occurred:\", err)\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udd39 <strong>8. Working with JSON Data<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">API responses are usually JSON, so you can manipulate them as dictionaries or lists.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import requests\n\nurl = \"https:\/\/jsonplaceholder.typicode.com\/users\"\nresponse = requests.get(url)\nusers = response.json()\n\nfor user in users:\n    print(f\"Name: {user&#91;'name']}, Email: {user&#91;'email']}, City: {user&#91;'address']&#91;'city']}\")\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output Example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Name: Leanne Graham, Email: Sincere@april.biz, City: Gwenborough\nName: Ervin Howell, Email: Shanna@melissa.tv, City: Wisokyburgh\n...\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udd39 <strong>9. Real-Life Example \u2013 Weather API<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Fetching weather data from <strong>OpenWeatherMap API<\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import requests\n\napi_key = \"YOUR_API_KEY\"\ncity = \"London\"\nurl = f\"http:\/\/api.openweathermap.org\/data\/2.5\/weather?q={city}&amp;appid={api_key}&amp;units=metric\"\n\nresponse = requests.get(url)\ndata = response.json()\n\nif response.status_code == 200:\n    print(f\"City: {data&#91;'name']}\")\n    print(f\"Temperature: {data&#91;'main']&#91;'temp']}\u00b0C\")\n    print(f\"Weather: {data&#91;'weather']&#91;0]&#91;'description']}\")\nelse:\n    print(\"Error:\", data&#91;\"message\"])\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output Example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>City: London\nTemperature: 18\u00b0C\nWeather: light rain\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udd39 <strong>10. Authentication with APIs<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Some APIs require authentication, e.g., API keys, tokens, or OAuth.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>url = \"https:\/\/api.example.com\/data\"\nheaders = {\"Authorization\": \"Bearer YOUR_ACCESS_TOKEN\"}\n\nresponse = requests.get(url, headers=headers)\nprint(response.json())\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udd39 <strong>11. Advanced Techniques<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Timeouts<\/strong>: Avoid waiting forever for a server response.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>requests.get(url, timeout=5)  # 5 seconds max\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Retrying Failed Requests<\/strong>: Use <code>requests.adapters<\/code> for automatic retries.<\/li>\n\n\n\n<li><strong>Streaming Large Data<\/strong>: Use <code>stream=True<\/code> for big files to avoid memory overload.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>with requests.get(\"https:\/\/example.com\/largefile\", stream=True) as r:\n    with open(\"largefile.zip\", \"wb\") as f:\n        for chunk in r.iter_content(chunk_size=8192):\n            f.write(chunk)\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\"><\/h2>\n","protected":false},"excerpt":{"rendered":"<p>\ud83c\udfaf Lesson Objective To learn how to interact with APIs using Python, send requests, handle responses, and work with data from external sources such as web services or third-party platforms. \ud83e\udde9 1. What Is an API? API (Application Programming Interface) allows one program to communicate with another. \u2699\ufe0f 2. Python Requests Module The requests module [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6,1],"tags":[],"class_list":["post-102","post","type-post","status-publish","format-standard","hentry","category-python-easy-course-outline","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/posts\/102","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=102"}],"version-history":[{"count":1,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/posts\/102\/revisions"}],"predecessor-version":[{"id":103,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/posts\/102\/revisions\/103"}],"wp:attachment":[{"href":"https:\/\/codetypingpro.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=102"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=102"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=102"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}