Understanding APIs and AI Integration
Covers what APIs are and why they matter for AI: requests and responses, endpoints, API keys, JSON, and RESTful design, with a worked Python example of calling a sentiment-analysis API.
{"contentFormat":"slides.v1","completion":{"requireAllSlides":true,"requireQuiz":true},"slides":[{"kind":"title","eyebrow":"Module 6: Coding for AI + Vibe Coding","title":"Understanding APIs and AI Integration","body":"Learn how to connect your code to powerful AI services using APIs. This module covers the fundamentals of RESTful APIs, authentication, error handling, and practical integration with real-world examples. Embrace Vibe Coding to write clear, intuitive, and enjoyable code.","outcomes":["Explain what an API is and why it's essential for AI integration","Identify key components of an API request and response","Handle authentication, errors, and rate limits in API calls","Integrate a real sentiment analysis API using Python"],"narration":"Welcome to Module 6, where we explore how APIs enable AI integration. By the end of this lesson, you'll be able to connect your code to AI services, handle common challenges, and write code that feels natural and efficient."},{"kind":"content","heading":"What is an API?","body":"An Application Programming Interface (API) is a set of rules that allows software programs to communicate. Think of it as a waiter in a restaurant: you (the client) order from the menu (the API endpoints), and the waiter brings your request to the kitchen (the server) and returns your food (the response).\n\nAPIs are crucial for AI because they provide access to pre-trained models without needing to build them from scratch. For example, you can use the Google Cloud Natural Language API to analyze sentiment, or the OpenAI API to generate text.\n\nKey components:\n- Endpoint: A specific URL (e.g., https://api.example.com/analyze)\n- HTTP Method: GET (retrieve), POST (create), PUT (update), DELETE (remove)\n- Headers: Metadata like authentication tokens and content type\n- Body: Data sent with the request (usually JSON)\n- Response: Data returned (usually JSON) with a status code (200 OK, 404 Not Found, etc.)","callout":{"variant":"note","title":"Real-World Example","text":"The Twitter API allows you to fetch tweets, post updates, and analyze trends. Developers use it to build social media dashboards, sentiment analysis tools, and chatbots."},"narration":"An API is like a digital waiter that connects your code to AI services. You send a request to an endpoint, and the API returns a response. This is how you leverage powerful AI without reinventing the wheel."},{"kind":"content","heading":"Authentication and Security","body":"Most APIs require authentication to ensure only authorized users access them. Common methods include:\n\n- API Key: A unique string sent in the request header (e.g., Authorization: Bearer YOUR_API_KEY). Simple but less secure.\n- OAuth 2.0: A more secure protocol that uses tokens. Common for APIs that access user data (e.g., Google, Facebook).\n\nBest practices:\n- Never hardcode keys in your code. Use environment variables or a secrets manager.\n- Rotate keys regularly.\n- Use HTTPS to encrypt data in transit.\n\nExample header with API key:\n
\nAuthorization: Bearer sk-1234567890abcdef\nContent-Type: application/json\n","callout":{"variant":"warning","title":"Security Alert","text":"If your API key is exposed (e.g., committed to GitHub), anyone can use it. Use .env files and add them to .gitignore. For production, use a secrets manager like AWS Secrets Manager."},"narration":"Authentication protects APIs from misuse. API keys are common, but OAuth is more secure for user-specific data. Always keep your keys secret and use environment variables."},{"kind":"content","heading":"Handling Errors and Rate Limits","body":"APIs can fail for many reasons. Always check the HTTP status code:\n\n- 2xx: Success (e.g., 200 OK, 201 Created)\n- 4xx: Client error (e.g., 400 Bad Request, 401 Unauthorized, 429 Too Many Requests)\n- 5xx: Server error (e.g., 500 Internal Server Error)\n\nRate limiting prevents abuse. If you exceed the limit, you'll get a 429 response. Handle it by:\n- Retrying after the time specified in the Retry-After header.\n- Implementing exponential backoff (wait longer between retries).\n\nPython example with error handling:\npython\nimport requests\nimport time\n\nurl = \"https://api.example.com/analyze\"\nheaders = {\"Authorization\": \"Bearer YOUR_API_KEY\"}\ndata = {\"text\": \"Great product!\"}\n\nfor attempt in range(3):\n response = requests.post(url, headers=headers, json=data)\n if response.status_code == 200:\n result = response.json()\n print(f\"Sentiment: {result['sentiment']}, Score: {result['score']}\")\n break\n elif response.status_code == 429:\n retry_after = int(response.headers.get(\"Retry-After\", 5))\n print(f\"Rate limited. Retrying in {retry_after} seconds...\")\n time.sleep(retry_after)\n else:\n print(f\"Error {response.status_code}: {response.text}\")\n break\n","callout":{"variant":"tip","title":"Rate Limit Headers","text":"Many APIs include headers like X-RateLimit-Remaining and X-RateLimit-Reset. Monitor these to stay within limits."},"narration":"Always handle errors gracefully. Check status codes, implement retries for rate limits, and log failures. This makes your integration robust and user-friendly."},{"kind":"content","heading":"Real-World Integration: Sentiment Analysis with TextBlob","body":"Let's integrate a free, real API: TextBlob (a Python library) for sentiment analysis. No API key needed! This demonstrates the same concepts as a cloud API.\n\nStep-by-step:\n1. Install TextBlob: pip install textblob\n2. Import and analyze:\n\npython\nfrom textblob import TextBlob\n\ntext = \"This product is amazing! I love it.\"\nblob = TextBlob(text)\nsentiment = blob.sentiment\n# sentiment.polarity ranges from -1 (negative) to 1 (positive)\n# sentiment.subjectivity from 0 (objective) to 1 (subjective)\n\nprint(f\"Polarity: {sentiment.polarity:.2f}\")\nprint(f\"Subjectivity: {sentiment.subjectivity:.2f}\")\n\nif sentiment.polarity > 0:\n print(\"Positive sentiment\")\nelif sentiment.polarity < 0:\n print(\"Negative sentiment\")\nelse:\n print(\"Neutral sentiment\")\n\n\nOutput:\n\nPolarity: 0.50\nSubjectivity: 0.60\nPositive sentiment\n\n\nThis mirrors how you'd call a cloud API like Google Cloud Natural Language, but without network requests or keys.","callout":{"variant":"exercise","title":"Try It Yourself","text":"Analyze the sentiment of a customer review in your native language. TextBlob supports multiple languages via translation. Experiment with different texts and observe the polarity scores."},"narration":"TextBlob is a simple Python library for sentiment analysis. It's a great way to practice API integration concepts without needing a cloud account. The same pattern applies to any REST API."},{"kind":"quiz","heading":"Check Your Understanding","questions":[{"question":"What does an HTTP status code of 429 indicate?","options":["Success","Unauthorized","Rate limit exceeded","Server error"],"questionId":"cmrf73k9u0027pd27i0vpsjk1"},{"question":"Which authentication method is more secure for APIs that access user data?","options":["API Key","OAuth 2.0","Basic Auth","No authentication"],"questionId":"cmrf73k9v0028pd272395jugf"},{"question":"In the TextBlob example, what does a polarity score of -0.8 indicate?","options":["Strongly positive sentiment","Strongly negative sentiment","Neutral sentiment","Subjective text"],"questionId":"cmrf73k9v0029pd27zgt5cfz2"}],"quizId":"qz_cmk7lkxgb002fg4p8d54nh13b"},{"kind":"summary","heading":"Key Takeaways","takeaways":["APIs are interfaces that allow software to communicate, essential for integrating AI services.","Always authenticate using API keys or OAuth, and keep credentials secure.","Handle HTTP errors and rate limits with proper status code checks and retry logic.","Use real APIs like TextBlob (free) or cloud APIs (Google, OpenAI) to practice integration.","Vibe Coding: write clear, readable code and enjoy the process."],"narration":"You've learned the essentials of API integration: what APIs are, how to authenticate, handle errors, and make real calls. Keep practicing with different APIs to build confidence. Happy coding!"}]}