-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_demo.py
More file actions
314 lines (219 loc) · 15.1 KB
/
Copy pathapi_demo.py
File metadata and controls
314 lines (219 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# -*- coding: utf-8 -*-
"""api_demo.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1cIve4ghk9qNTlFijvtDLfUWh1OsI9rC6
# **API Demonstration**
## **Introduction**
This assignment demonstrates foundational skills in working with databases and external data sources using Python. The objective is to show an understanding of core concepts such as database querying, file input/output operations, and basic API interaction, without relying on complex integrations or advanced analytics.
In the first part of the assignment, Python is used to interact with a database, execute queries, and export results to external files such as CSV and text reports. The second part focuses on making a simple API call to a public web service, processing the JSON response, and displaying the results in a clear and readable format. Together, these components highlight practical data-handling skills, user interaction, error handling, and clean code organization using functions.
## **REST Countries API**
This notebook demonstrates a simple and effective example of calling a public API in Python and processing the response. The objective of this task is to show basic API usage skills, including user interaction, JSON parsing, and error handling, without introducing unnecessary complexity.
In this demonstration, the script:
1. Prompts the user to enter a country name using `input()`
2. Builds an API request URL dynamically based on the user’s input
3. Makes a successful API call to a public REST API
4. Parses the JSON response returned by the API
5. Extracts and displays key country information in a readable format
6. Handles common errors such as invalid input or failed requests using `try/except`
## **API Used**
- **REST Countries API** (No API key required)
- **Endpoint:** `https://restcountries.com/v3.1/name/{country_name}`
## **Description**
The REST Countries API provides structured data about countries around the world. In this example, the user enters the name of a country, and the program retrieves details such as the capital city, population, geographic region, and official languages. This API was chosen because it is easy to use, publicly accessible, and well-suited for demonstrating basic API functionality.
## **Purpose**
This demonstration focuses only on showing that an API can be successfully called, the response can be parsed, and meaningful information can be displayed. It does not integrate with a database or perform advanced data analysis, in accordance with the assignment requirements.
## **Import Required Libraries**
To make the API call and process the response, this script uses only Python’s built-in libraries. No external installations are required, which keeps the demonstration simple and portable.
The following libraries are used:
- **`urllib.request`** – Used to make HTTP requests to the REST Countries API
- **`json`** – Used to parse the JSON response returned by the API into Python objects
"""
# Import urllib.request to make HTTP requests (API calls) using only built-in Python libraries
import urllib.request
# Import json to convert the API's JSON response into Python dictionaries/lists
import json
# Simple confirmation message so we know imports worked
print("Libraries imported successfully!")
"""Now that the required libraries are imported, we can prompt the user for a country name. This input will be used to build the API request URL in the next step.
## **Create the API Function**
In this step, we create a reusable function that handles the core API interaction. The function accepts a country name provided by the user, constructs the appropriate REST Countries API request, and retrieves the response from the server.
Once the data is returned, the function parses the JSON response and extracts key information such as the country’s name, capital, population, region, languages, and currency details. To ensure robustness, basic error handling is implemented using `try/except` blocks to catch invalid inputs, network errors, and JSON parsing issues. The cleaned and structured data is then returned as a Python dictionary for easy display in the next step.
"""
def fetch_country_data(country_name):
"""
Fetch country information from the REST Countries API.
Args:
country_name (str): Name of the country (e.g., India, USA, Japan)
Returns:
dict: A dictionary of country details, or None if an error occurs
"""
try:
# 1) Construct the API URL using the user's input
url = f"https://restcountries.com/v3.1/name/{country_name}"
# 2) Make the API request (open the URL and get a response)
with urllib.request.urlopen(url) as response:
# 3) Read the response (bytes), decode to string, and parse JSON into Python objects
data = json.loads(response.read().decode("utf-8"))
# 4) The API returns a list of matching countries; use the first result
country = data[0]
# Extract key fields safely using .get() to avoid KeyErrors
# Common (short) country name (e.g., "India")
name = country.get("name", {}).get("common", "N/A")
# Official country name (e.g., "Republic of India")
official_name = country.get("name", {}).get("official", "N/A")
# Capital is usually a list (e.g., ["New Delhi"]); take the first value if present
capital_list = country.get("capital", ["N/A"])
capital = capital_list[0] if capital_list else "N/A"
# Total population (integer)
population = country.get("population", 0)
# Region and subregion (strings)
region = country.get("region", "N/A")
subregion = country.get("subregion", "N/A")
# Languages are returned as a dictionary (e.g., {"hin":"Hindi","eng":"English"})
# Join all language names into one readable string
languages_dict = country.get("languages", {})
languages = ", ".join(languages_dict.values()) if languages_dict else "N/A"
# Currencies are returned as a dictionary (e.g., {"INR": {"name": "...", "symbol": "₹"}})
# Convert to a readable list like: "Indian rupee (₹)"
currencies_dict = country.get("currencies", {})
currencies = []
for code, info in currencies_dict.items():
currency_name = info.get("name", "")
currency_symbol = info.get("symbol", "")
currencies.append(f"{currency_name} ({currency_symbol})".strip())
currencies_str = ", ".join(currencies) if currencies else "N/A"
# Area in square kilometers (number)
area = country.get("area", 0)
# Flag emoji (if available)
flag = country.get("flag", "")
# Return a clean dictionary that the main program can print nicely
return {
"name": name,
"official_name": official_name,
"capital": capital,
"population": population,
"region": region,
"subregion": subregion,
"languages": languages,
"currencies": currencies_str,
"area": area,
"flag": flag
}
# Basic error handling for common API issues
except urllib.error.HTTPError as e:
# HTTP errors include 404 (not found), 500 (server issues), etc.
if e.code == 404:
print(f"Error: Country '{country_name}' not found.")
else:
print(f"HTTP Error: {e.code}")
return None
except urllib.error.URLError as e:
# Network-related issues (no internet, DNS failure, etc.)
print(f"Network Error: Unable to connect to API. {e.reason}")
return None
except json.JSONDecodeError as e:
# If the response isn't valid JSON (rare, but possible)
print(f"JSON Parsing Error: {e}")
return None
except Exception as e:
# Catch-all for any unexpected errors
print(f"Unexpected Error: {e}")
return None
# Confirmation message so we know the function cell ran successfully
print("fetch_country_data() function created!")
"""With the API function now defined, we can use it to retrieve country information based on user input. In the next step, the program will prompt the user for a country name and display the fetched results in a clear and readable format.
## **Create Display Function**
In this step, we define a function responsible for presenting the country information in a clear and user-friendly format. Instead of printing raw JSON data, the function formats each field with labels, spacing, and separators so the output is easy to read and interpret.
The function checks whether valid data was returned from the API before attempting to display it, ensuring graceful handling of errors. This separation of data retrieval and data presentation helps keep the code organized, readable, and easy to maintain.
"""
def display_country_info(country_data):
"""
Display country information in a readable format.
Args:
country_data (dict): Country information dictionary returned by fetch_country_data()
"""
# If the API function returned None (error or no results), there is nothing to display
if country_data is None:
print("No data to display.")
return
# Print a clean header with separators for readability
print("\n" + "=" * 50)
print(f" {country_data['flag']} COUNTRY INFORMATION {country_data['flag']}")
print("=" * 50)
# Display each field in a structured, labeled format
print(f"\n Name: {country_data['name']}")
print(f" Official Name: {country_data['official_name']}")
print(f" Capital: {country_data['capital']}")
# Format population and area with commas for easier reading (e.g., 1,234,567)
print(f" Population: {country_data['population']:,}")
print(f" Area: {country_data['area']:,} km²")
# Regional details
print(f" Region: {country_data['region']}")
print(f" Subregion: {country_data['subregion']}")
# Language and currency details
print(f" Languages: {country_data['languages']}")
print(f" Currencies: {country_data['currencies']}")
# Footer separator
print("\n" + "=" * 50)
# Confirmation message so we know this function cell ran successfully
print("display_country_info() function created!")
"""Now that the display function is ready, we can connect everything together in a simple interactive flow. In the next step, the user will enter a country name, the API will fetch the data, and the results will be printed in the formatted output.
## **Main Function**
In this step, we create the main driver function that brings the entire API demonstration together. The main function is responsible for handling the user interaction and controlling the program flow.
Specifically, it:
1. Prompts the user to enter a country name using `input()`
2. Validates the input to ensure it is not empty
3. Calls the API function (`fetch_country_data`) to retrieve country details
4. Passes the results to the display function (`display_country_info`) for clean, readable output
This keeps the notebook organized by separating responsibilities: one function fetches data, one function displays it, and `main()` coordinates everything.
"""
def main():
"""Main function to demonstrate API calls end-to-end."""
# Print a simple title/header for the demo output
print("=" * 50)
print(" REST COUNTRIES API DEMO")
print("=" * 50)
# Brief description + examples so the user knows what to type
print("\nThis program fetches information about any country.")
print("Examples: India, USA, Japan, France, Brazil, Australia\n")
# 1) Ask the user for a country name (interactive requirement)
country_name = input("Enter country name: ")
# 2) Validate input (basic check to avoid empty/blank values)
if not country_name.strip():
print("Error: Please enter a valid country name.")
return # Exit early if input is invalid
# Let the user know we are about to make the API call
print(f"\nFetching data for '{country_name}'...")
# 3) Call the API function to fetch country data
result = fetch_country_data(country_name)
# 4) If we got valid data back, display it nicely; otherwise show an error message
if result:
display_country_info(result)
print("\nAPI demonstration complete!")
else:
print("\nFailed to fetch country data. Please try again.")
# Confirmation message so we know the main() function cell ran successfully
print("main() function created!")
"""With all functions now defined, the program is ready to be executed. In the next step, we will call the `main()` function to start the interactive API demonstration.
## **Run the Program**
Now that all functions are defined, we can run the complete API demonstration from start to finish. This step triggers the interactive flow where the program asks for a country name, sends a request to the REST Countries API, parses the JSON response, and prepares the key fields for display.
Run the cell below and enter a country name when prompted (for example: **India**, **United States**, **Japan**, **France**, **Brazil**, or **Germany**). If the input is valid and the API call is successful, we will see a neatly formatted output with details such as capital, population, region, languages, and currencies.
"""
# Run the main function to start the interactive API demo
main()
"""**Output Check:**
The program ran successfully and returned country information from the REST Countries API. This confirms that the API request worked, the JSON response was parsed correctly, and the results were displayed in a readable format with basic input validation and error handling in place.
## **Test with Different Countries**
To further confirm that the API demo works reliably, we can run the program multiple times using different country names. This helps verify that the script handles a variety of valid inputs and consistently returns correctly formatted results.
Simply re-run the cell below and enter a new country name each time we are prompted (for example: **Japan**, **India**, **Germany**, **Brazil**, or **United Kingdom**).
"""
# Run the program again to test with a different country name
# (Re-run this cell as many times as you want)
main()
"""**Output Check:**
The second test run also executed successfully. The program accepted a new input (“France”), made a fresh API request, parsed the JSON response, and displayed the correct country details in the same formatted structure—confirming the script works consistently across different countries.
## **Conclusion**
This assignment successfully demonstrates the use of Python for database interaction, file handling, and basic API integration. By querying data, exporting results to external files, and generating simple reports, the first part highlights practical database and file I/O skills.
The API demonstration further shows the ability to make external web requests, parse JSON responses, handle user input, and present information in a readable format. Overall, the assignment emphasizes clean code structure, modular function design, and basic error handling, providing a solid foundation for working with databases and external data sources in real-world applications.
"""