Here are two reference programs for the post-lecture exercise, demonstrating the core concepts from the API Fundamentals course. Both programs use the requests library to interact directly with OpenAI's API, providing transparency into HTTP mechanics. They also use the dotenv library to load environment variables from the .env file, which in this case is used for storing our API keys.
This project uses pyproject.toml for dependency management, compatible with modern Python package managers:
Dependencies:
requests- For transparent HTTP API interactionspython-dotenv- For loading API keys from.envfiles
Installation with uv (recommended):
uv syncInstallation with pip:
pip install requests python-dotenvStoring API keys in .env files is a security best practice that prevents accidentally exposing credentials when sharing code.
-
Copy the example environment file:
cp .env.example .env
-
Get your OpenAI API key:
- Go to https://platform.openai.com/
- Sign in or create an account
- Navigate to "API Keys" section
- Create a new API key
-
Edit the .env file: Open
.envin a text editor and replaceyour-api-key-herewith your actual API key:OPENAI_API_KEY=sk-proj-xxxxxxxxxxxxxThe API key format:
- Starts with
sk-proj-(for project keys) orsk-(for older format) - Followed by additional characters
- Keep it secret and never commit it to version control
- Starts with
This process works similarly for other providers (like Anthropic), but the idea is the same.
An interactive command-line chatbot that demonstrates core API concepts:
- HTTP Headers: Sets up authorization (
Authorization: Bearer), content type - Request Body: Sends JSON payload with model selection and conversation messages
- Statelessness: Includes full conversation history in each request (REST principle)
- Response Parsing: Extracts assistant's message from JSON response
Key Features:
- Maintains conversation context
- Commands:
clear(reset conversation),system(change prompt),quit/exit - Error handling for network issues and API errors
A command-line tool for analyzing images using OpenAI's GPT-4o-mini vision capabilities:
- Multi-modal Content: Sends both text and image in a single API request
- Base64 Encoding: Converts binary image data to text format for JSON transport
- Content-Type Handling: Maps image formats to appropriate MIME types
- Same API Endpoint: Uses the same
/v1/chat/completionsendpoint as text-only requests
Key Features:
- Supports jpg, png, gif, webp formats
- Custom prompts via
--promptflag - Comprehensive error handling
- File validation before upload
python openai_chatbot.pySample interaction:
==================================================
OpenAI Command Line Chatbot
==================================================
Commands:
• Type 'quit' or 'exit' to end
• Type 'clear' to reset conversation
• Type 'system' to change system message
==================================================
You: What are APIs?
GPT:
APIs (Application Programming Interfaces) are standardized ways for different software applications to communicate and share data with each other, acting like a contract that defines how programs can request services and exchange information.
You: Can you give me an example?
GPT:
Sure! A common example is a weather app on your phone. When you open it, the app uses a weather service's API to request current conditions for your location. The API processes this request and sends back data like temperature, humidity, and forecast, which your app then displays in a user-friendly format. The app doesn't need to collect weather data itself—it just asks the weather service's API for the information it needs.
You: clear
Conversation cleared.
You: exit
Goodbye!
Basic usage:
python image_analyzer.py photo.jpgWith custom prompt:
python image_analyzer.py screenshot.png --prompt "What UI elements are visible in this interface?"Example output:
==================================================
Analyzing Image: photo.jpg
==================================================
Processing image...
Analysis Result:
This image shows the famous Shibuya Crossing in Tokyo, Japan, captured during what appears to be a quiet moment, likely during the pandemic period given the notably sparse foot traffic.
Both programs demonstrate the three key parts of HTTP requests:
-
Headers - Metadata about the request:
Authorization: Bearer token authentication credentialContent-Type: Indicates JSON payload
-
Body - The actual data being sent:
- JSON format with model, messages, and parameters
- For images: includes base64-encoded data
-
Method - POST for sending data and expecting response
The programs parse responses following standard patterns:
- Status Codes: Check for 200 (success) vs errors (4xx, 5xx)
- JSON Parsing: Extract content from structured response
- Error Messages: Parse error details when requests fail
- Statelessness: Each request contains complete context (full conversation history)
- Uniform Interface: Same endpoint (
/v1/chat/completions) for different content types - Standard Methods: POST for data submission, consistent URL structure
- Environment Variables: API keys stored in
.env, never hardcoded - Error Handling: Sensitive information not exposed in error messages
- Timeout Settings: Prevent hanging on slow connections
- Cause: Missing or incorrectly named
.envfile - Solution: Ensure
.envexists in the same directory and contains your API key
- Cause: Incorrect or expired API key
- Solution: Verify your API key in the Anthropic console and update
.env
- Cause: Your API key has no remaining credits or usage quota
- Solution:
- Check your usage and billing at https://platform.openai.com/usage
- Add credits to your account or upgrade your plan
- For new accounts, ensure you've added a payment method and purchased credits
- Cause: Large image file or slow network connection
- Solution: Try a smaller image or increase the timeout value in the code
- Cause: Trying to analyze an unsupported image type
- Solution: Convert image to jpg, png, gif, or webp format
- Cause: Hitting API rate limits
- Solution: Wait a few moments before making more requests
- Cause: No internet connection or firewall blocking
- Solution: Check your internet connection and firewall settings