What is an API?
An API (Application Programming Interface) is like a waiter at a restaurant. You tell it what you want, and it brings you the data. But APIs do more than just fetch information. They’re the bridges that connect your code to other systems. With APIs, you can:- Pull customer data from your CRM (Salesforce, HubSpot)
- Get order information from Shopify or WooCommerce
- Send messages through Slack or email services
- Use AI models from OpenAI or Anthropic
requests Module
The requests module is a popular third-party Python library used to send HTTP requests. It simplifies communication with web servers and REST APIs.
Install the library using:
Common HTTP Methods
Example: GET Request
Example: POST Request
Useful Response Attributes
Common Status Codes
Let’s get real weather data using a free weather API:
First install requests:
pip install requestsUnderstanding the response
The API sends back data in JSON format (like a Python dictionary):current, so to get it:
Extract what you need
Now you can pull out specific information:How it works
- You send a request to the API’s URL with parameters (like coordinates)
- The API processes your request and finds the data
- You receive JSON data back with the information
- You extract the specific parts you need
Practice & Exercises
To reinforce what you’ve learned in this section (making API requests, reading JSON response payloads, extracting nested properties, and querying coordinates dynamically), practice with these interactive notebooks:Follow-Along Practice
Practice submitting coordinate parameters to weather APIs using requests, extracting nested dictionary properties, and writing query wrappers to compare temperature statistics.💻 VS Code | 🚀 Colab | 📥 Download
Practice Exercises
Test your knowledge with hands-on exercises on querying Indian cities, writing get_weather_details for temperature/wind outputs, and adding exception handling to API calls.💻 VS Code | 🚀 Colab | 📥 Download
What’s next?
Now that you know how to connect to web APIs, let’s learn how to store API keys and database credentials securely using environment variables.Working with Environment Variables
Learn to manage secrets with .env files