Introduction
Knowing syntax is one thing. Building a real project is another. In this post, we’ll cover:
- How to call APIs and handle JSON responses
- Structuring Python projects across multiple files
- The Contact Book mini-project that ties everything together
By the end, you’ll have a blueprint for any Python application.
API Integration: Fetching Live Data
APIs (Application Programming Interfaces) allow your code to talk to external services. Most modern APIs return JSON.
Using the requests library
python
import requests
response = requests.get("https://api.github.com/users/octocat")
if response.status_code == 200:
data = response.json() # Parse JSON
print(data["name"])
else:
print("API call failed")
Common API Workflow
- Send HTTP request (GET, POST, etc.)
- Check status code (200 = OK, 404 = Not Found, 500 = Server Error)
- Parse JSON response
- Handle errors gracefully
Example: Weather API
python
def get_weather(city):
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid=YOUR_KEY"
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # Raises exception for 4xx/5xx
return response.json()
except requests.exceptions.RequestException as e:
return {"error": str(e)}
Always set a timeout and use raise_for_status().
Multi-File Project Structure
A professional Python project is never one huge file. You split by responsibility.
Example Structure:
text
contact_book/
│
├── main.py # Entry point
├── contact_manager.py # Business logic
├── file_handler.py # JSON read/write
├── utils.py # Helper functions
└── data/
└── contacts.json # Storage
How Imports Work
python
# In main.py from contact_manager import add_contact from file_handler import load_contacts
Use absolute imports for clarity. Avoid from module import *.
if __name__ == "__main__" Explained
This ensures code runs only when the script is executed directly, not when imported.
python
# main.py
def main():
print("Contact Book Started")
if __name__ == "__main__":
main()
Contact Book Mini Project: Tying It All Together
This project uses:
- OOP (Contact class)
- File handling (JSON storage)
- Exception handling
- Multi-file structure
Contact Class (OOP)
python
# models.py
class Contact:
def __init__(self, name, phone, email):
self.name = name
self.phone = phone
self.email = email
def to_dict(self):
return {"name": self.name, "phone": self.phone, "email": self.email}
JSON Storage Handler
python
# storage.py
import json
def save_contacts(contacts):
with open("data/contacts.json", "w") as file:
json.dump([c.to_dict() for c in contacts], file, indent=4)
def load_contacts():
try:
with open("data/contacts.json", "r") as file:
data = json.load(file)
return [Contact(**item) for item in data]
except FileNotFoundError:
return []
Main Logic
python
# main.py
def add_contact(contacts):
name = input("Name: ")
phone = input("Phone: ")
email = input("Email: ")
contacts.append(Contact(name, phone, email))
save_contacts(contacts)
This is production-style code: modular, reusable, and error-resistant.
Skills You Build
- Logic building: Breaking features into small functions
- Debugging: Using print statements and try-except
- Real-world readiness: Code that other developers can understand
Leave a Reply