import socket
import requests
# Step 1: DNS Lookup
= "example.com"
domain print(f"Looking up IP address for: {domain}")
= socket.gethostbyname(domain)
ip_address print(f"IP address of {domain} is {ip_address}")
# Step 2: HTTP Request
print(f"\nSending HTTP GET request to {domain}...")
print(f"\nThe response is printed below:")
= requests.get(f"http://{domain}")
response
# Step 3: Print Response
print(f"\nResponse Status Code: {response.status_code}")
print(f"\nCode of 200 means things went as planned.")
print("Response Headers:")
print(response.headers)
print("\nFirst 500 characters of the HTML:")
print(response.text)
# Step 4: Save response to an HTML file
= "response.html"
filename with open(filename, "w", encoding="utf-8") as f:
f.write(response.text)
print(f"\nFull HTML response saved to {filename}.")
print(f"\nOpen the HTML file in your browser.")
APIs & Internet Fundamentals
The Internet
What is the internet?
“A series of tubes” is a phrase coined originally as an analogy by then-United States Senator Ted Stevens (R-Alaska) to describe the Internet in the context of opposing network neutrality.[1] On June 28, 2006, he used this metaphor to criticize a proposed amendment to a committee bill. The amendment would have prohibited Internet Access providers such as AT&T, Comcast, Time Warner Cable, and Verizon Communications from charging fees to give some companies’ data a higher priority in relation to other traffic.”
What is the internet, really???
The Internet is a global system of interconnected computers and devices that communicate using standardized protocols—primarily the Internet Protocol Suite (TCP/IP)—to share information and services. These devices form a vast network-of-networks, exchanging data over physical infrastructure such as fiber-optic cables, satellites, and wireless technologies.
The Internet is a decentralized system where independently operated networks agree to exchange data.
The internet is a global network of devices connected via cables (fiber, copper, etc.), satellites, or wireless systems. Devices that connect to the internet communicate with each other by exchanging data using various sets of rules called protocols. Each protocol governs how a specific type of communication is carried out. For example, sending an email uses the SMTP protocol, while loading a webpage in your browser typically uses HTTPS.
Therefore, when you open Gmail in your browser and send an email, multiple protocols are at work: HTTPS is used to load the Gmail web interface and securely interact with it, while SMTP is used behind the scenes to transmit the email to the recipient’s mail server.
Each protocol has it’s own rules simliar to the grammar rules of a language (e.g. verb tense, sentence structure).
Just as using proper grammar helps people understand each other clearly and effectively, the rules of a given protocol ensure that devices can reliably exchange a given type of data (e.g. email).
One of the most important protocols on the modern internet is HyperText Transfer Protocol Secure (HTTPS), which smartphones and laptops use—typically through web browsers—to securely interact with websites.
We dive into some of the rules later in this chapter.
First, we need a better understanding for the kinds of devices that get connected to the Internet. When we say device, we mean any of the following:
- Client devices – such as smartphones, laptops, tablets, and desktop computers that request data or services from servers.
- Servers – computers (physical or virtual) that host websites, applications, files, or other data, and respond to client requests.
- Routers and switches – networking hardware that directs traffic across the internet and within local networks.
- Internet of Things (IoT) devices – smart thermostats, cameras, watches, appliances, and other gadgets that send and receive data.
- Data center infrastructure – large-scale systems including virtual machines and containerized environments that power cloud services.
- Edge devices – equipment like content delivery nodes or local caching servers that bring data closer to users for faster access.
Client
Server
What happens when you type a URL into a browser (e.g. Chrome, Safari)?
Say you type: https://www.example.com into your browser.
This triggers a sequence of events involving several systems:
Step 1: DNS Lookup
DNS (Domain Name System) is the internet’s phonebook. Imagine a look-up table where every text URL is matched to the the IP address (a number that uniquely identifies the device or server).
You typed www.example.com. Your device asks a DNS server: “What is the IP address of this domain?” The DNS server replies with something like: 93.184.216.34. Now your computer knows where to send the request.
Step 2: HTTP/HTTPS Request Now that you know the server’s address:
Your browser sends an HTTP (or HTTPS) request to the IP address. This request says: “Please send me the web page for / (the homepage) of www.example.com.” If it’s HTTPS, the request is encrypted, so no one in between can read it.
HTTP(S) stands for HyperText Transfer Protocol (Secure). A “protocol” is simply a formal set of rules for how computers communicate. Think of it like a shared language or etiquette for machines. These rules define how a client (like your browser) and a server (like example.com) exchange requests and responses.
Step 3: Client-Server Architecture
Your device (the client) made the request. The server (at 93.184.216.34) receives it, processes it, and sends back the necessary files — HTML, CSS, JavaScript, images, etc. You can think of this like a waiter (client) asking the kitchen (server) for your order (website) and bringing it back to your table (browser).
Step 4: Browser Renders the Page
Your browser receives the code and files. It renders the webpage visually — drawing the layout, loading images, executing JavaScript, and displaying the site
Below is a code snippet that illustrates
Exercise 1
HTTP response codes are standardized 3-digit numbers sent by a web server to indicate the outcome of a client’s request. They let the client know whether the request was successful, redirected, resulted in an error, or requires additional action.
Two of the most common codes you will encounter are 200 and 404.
Code Category | Code | Name | Description |
---|---|---|---|
1xx Informational | 100 | Continue | The initial part of the request has been received, and the client should continue. |
101 | Switching Protocols | Server is switching protocols as requested (e.g., HTTP to WebSocket). | |
2xx Success | 200 | OK | The request succeeded, and the response contains the requested data. |
201 | Created | A new resource was successfully created (e.g., after a POST request). | |
202 | Accepted | The request has been received but not yet processed. | |
204 | No Content | The request was successful, but there is no content to return. | |
3xx Redirection | 301 | Moved Permanently | The resource has permanently moved to a new URL. |
302 | Found | The resource is temporarily at a different URL. | |
304 | Not Modified | The cached version is still valid; no need to resend data. | |
4xx Client Errors | 400 | Bad Request | The server couldn’t understand the request due to malformed syntax. |
401 | Unauthorized | Authentication is required or failed. | |
403 | Forbidden | The server understands the request but refuses to authorize it. | |
404 | Not Found | The requested resource could not be found. | |
405 | Method Not Allowed | The HTTP method is not supported for this resource. | |
5xx Server Errors | 500 | Internal Server Error | A generic server error — something went wrong on the server. |
502 | Bad Gateway | The server received an invalid response from an upstream server. | |
503 | Service Unavailable | The server is temporarily unavailable (e.g., overloaded or down for maintenance). | |
504 | Gateway Timeout | The upstream server failed to respond in time. |
Headers are a core part of the HTTP protocol (i.e. the agreed upon rules of sending information across the internet). Headers take the form of key-value pairs which are sent between a client and server and carry metadata about the request or response (e.g. such as content type, caching rules, and encoding). Headers help browsers and servers understand how to handle the data being exchanged. Below is a description of the headers that were returned from the example above.
Header (key: value pair) | Meaning |
---|---|
Accept-Ranges: bytes |
The server supports partial content downloads (e.g., resuming a download from a byte offset). |
Content-Type: text/html |
The response body is HTML — browsers know to render it as a webpage. |
ETag |
A unique ID (hash) representing this specific version of the file. Used for efficient caching. |
Last-Modified |
Timestamp of the last modification to the resource. Useful for cache validation. |
Vary: Accept-Encoding |
Indicates that the response varies depending on how the client encodes requests (e.g., gzip). |
Content-Encoding: gzip |
The response is compressed using gzip. The browser will decompress it automatically. |
Content-Length: 648 |
Size of the response body in bytes after compression. |
Cache-Control: max-age=3241 |
Tells the browser it can cache this resource for 3,241 seconds (~54 minutes). |
Date |
The date and time when the response was generated by the server. |
Connection: keep-alive |
Keeps the TCP connection open for reuse, improving performance for multiple requests. |
HTTP/HTTPS
Ealier we said that a “protocol” is simply a formal set of rules for how computers communicate (exchange requests and responses). Let’s look at what some of those rules are.
In the HTTP protocol, the commands used to tell the server what action the client wants to perform are called HTTP methods (or sometimes “verbs”)
The HTTP protocol includes:
Rules for message structure (request/response format) Allowed methods (GET, POST, etc.) Status codes (200, 404, 500, etc.) Headers (metadata) Optional message body Rules for connection management (e.g., keep-alive)
What IS the Internet?
The internet is a global network of interconnected computers that communicate using standardized protocols. When you’re building digital products, you’re essentially building on top of this massive infrastructure.
Think of it as three layers:
- Physical layer: Cables, fiber optics, wireless signals, satellites
- Network layer: Routers, switches, and protocols that move data
- Application layer: Websites, apps, and services — this is where your products live
Key Infrastructure Components
Internet Service Providers (ISPs)
- Tier 1: Backbone providers (AT&T, Verizon, Level 3)
- Tier 2: Regional providers that buy from Tier 1
- Tier 3: Local ISPs that serve consumers
When users complain about slow loading, it’s often their ISP, not your app. This hierarchy affects how you think about hosting locations and performance expectations.
Data Centers & The Cloud
- Massive server farms around the world
- Content Delivery Networks (CDNs) — bring content closer to users
- Edge computing — processing data closer to where it’s generated
Modern apps distribute globally through CDNs and multiple regions. If AWS US-East goes down (and it does), your European users keep working. AI processing at the edge means lower latency for real-time features.
Essential Protocols & Technologies
DNS (Domain Name System)
- What it does: Translates
google.com
→142.250.190.78
- Why it matters: Humans remember names, computers need numbers
- How it works: Hierarchical system of DNS servers worldwide
DNS is often the invisible bottleneck. Slow DNS makes your app feel slow even when your servers are blazing fast. Smart founders use multiple DNS providers and aggressive caching.
IP Addresses & Routing
- IPv4:
192.168.1.1
(we’re running out of these) - IPv6:
2001:0db8:85a3::8a2e:0370:7334
(the inevitable future) - Routing: How data finds the best path across networks
The IPv4 shortage means higher hosting costs and eventual IPv6 migration. Geographic routing lets you serve users from the closest servers.
TCP/IP Stack
- Application Layer: HTTP, HTTPS, FTP, SMTP — your APIs live here
- Transport Layer: TCP (reliable) vs UDP (fast)
- Internet Layer: IP routing and addressing
- Physical Layer: Actual cables and wireless signals
HTTPS is no longer optional — it’s required for user trust, SEO, and modern browser features. Choose TCP for payments and critical data, UDP for gaming and real-time features where speed beats reliability.
Watch this video for the big picture:
Step-by-step: What happens when you visit a website
The Journey of a Web Request
- You type
google.com
into your browser - DNS lookup: Your computer asks “What’s the IP address for google.com?”
- Checks local cache first
- Asks your ISP’s DNS server
- May query root servers, then .com servers, then Google’s servers
- DNS response: Returns something like
142.250.190.78
- TCP handshake: Your computer establishes a reliable connection
- SYN: “Can we talk?”
- SYN-ACK: “Yes, let’s talk”
- ACK: “Great, let’s start”
- HTTP request: Your browser sends a request
http GET / HTTP/1.1 Host: google.com User-Agent: Mozilla/5.0...
- Server processing: Google’s server processes your request
- HTTP response: Server sends back HTML, CSS, JavaScript
- Browser rendering: Your browser assembles and displays the page
- Additional requests: Browser fetches images, stylesheets, scripts
Why This Matters for Developers
Understanding this flow helps you: - Debug performance issues — where are the bottlenecks? - Optimize loading times — reduce DNS lookups, use CDNs - Handle errors gracefully — network timeouts, DNS failures - Design better APIs — minimize round trips, cache effectively
The Modern Internet Architecture
Content Delivery Networks (CDNs)
Instead of everyone hitting one server, CDNs distribute content globally:
User in Tokyo → Tokyo CDN server (fast!)
User in London → London CDN server (fast!)
User in NYC → NYC CDN server (fast!)
A user in Australia waiting 2 seconds for your US server vs. 0.2 seconds for a Sydney CDN server — that 10x difference shows up in conversion rates.
Popular CDNs: Cloudflare (free tier), AWS CloudFront, Google Cloud CDN
Load Balancers
Distribute traffic across multiple servers: - Round robin: Request 1 → Server A, Request 2 → Server B - Least connections: Send to server with fewest active connections - Geographic: Route based on user location
When one server crashes, load balancers route to healthy ones. When traffic spikes, they distribute the load. Essential for anything beyond a side project.
Microservices & APIs
Modern apps aren’t monoliths — they’re collections of services:
Frontend App → Authentication API
→ User Profile API
→ Payment API
→ Notification API
This architecture lets you scale what matters, gives teams independence, and makes debugging easier. Problem with payments? Check the payment service logs, not the entire application.
What an API Is (and Why You’ll Use Them Constantly)
Watch this video first:
API in plain English
API = Application Programming Interface
It’s a set of rules for how software talks to other software.
Restaurant analogy:
- The API is the waiter
- Your app is the customer
- The kitchen is the server
- The menu is what’s available via the API
Your app sends a request → API delivers it → response comes back.
Instead of building a payment processor from scratch, you use Stripe’s API. Instead of training your own AI model, you call OpenAI’s API. APIs let you focus on what makes your product unique while leveraging existing solutions for everything else.
API Keys — Your Digital Passport
An API key is like a password for your app when it talks to another service.
When you’ll need API keys
- OpenAI — for AI features
- Zapier workflows — for automation
- Frontend to backend — your app’s internal communication
- Stripe — for payments
- SendGrid — for emails
- Analytics services — for tracking
Most apps end up with 10+ API keys pretty quickly. Each one represents functionality you’re getting instantly instead of building over months.
Example request header
Authorization: Bearer sk-abc123
API Authentication Methods
Beyond API keys, you’ll encounter these authentication methods:
- OAuth 2.0 — for accessing user data from platforms like Google, GitHub, Twitter
- JWT (JSON Web Tokens) — for stateless authentication in your own APIs
- Bearer tokens — commonly used with AI services
API Security Basics
- Never hardcode API keys — use environment variables
- Rotate keys regularly — especially if compromised
- Use HTTPS always — never send keys over HTTP
- Respect rate limits — avoid getting blocked
Connecting Everything Together
Let’s say your app does this:
- A user uploads a file
- Your backend sends that file to OpenAI
- OpenAI returns a summary
- You store the summary in your database
- Zapier sends the summary to Slack or Google Sheets
All of that happens through APIs and API keys.
Common tools you’ll use:
AI & ML APIs
- OpenAI API — GPT models for text generation, summarization, chat
- Anthropic Claude — advanced reasoning and analysis
- Hugging Face — open-source models and transformers
- Google Cloud AI — vision, translation, speech recognition
Automation & Integration
- Zapier — to automate tasks (like sending data to Slack or Sheets)
- Webhooks — real-time notifications when events happen
Data & Backend
- Firebase / Supabase — to store and manage your app’s data
- Your own custom API — to connect your app’s frontend to its backend logic
Payments & Business
- Stripe API — to handle payments, billing, and subscriptions
Real Startup Use Cases (Your Actual Day-to-Day)
Here’s what you’ll actually be doing with APIs as a founder:
- Generate content with OpenAI
Blog posts, user summaries, chatbot replies, product descriptions
What’s a “ChatGPT Wrapper”?
You’ll hear this term a lot in startup circles. A ChatGPT wrapper is essentially an app that:
- Takes user input through a custom interface
- Sends that input to OpenAI’s API behind the scenes
- Formats and presents the response in a specific way
- Often adds specialized prompts, context, or processing
Examples of successful wrappers: - Copy.ai — marketing copy generation - Jasper — content writing for businesses
- Notion AI — writing assistance within Notion - GitHub Copilot — code completion in your editor
Why wrappers work: - Specialized UI — better than ChatGPT’s generic interface for specific tasks - Custom prompts — pre-engineered for particular use cases - Integration — built into existing workflows - Branding — your product, not OpenAI’s
The business model: You pay OpenAI ~$0.002 per 1K tokens, charge users $20-50/month for unlimited access to your specialized interface.
Automate workflows with Zapier
When new users sign up, auto-send welcome email + add to CRM + notify team in SlackProcess payments with Stripe
Charge credit cards, manage subscriptions, send receipts, handle refundsBuild a backend API for your app
Let your frontend make requests likeGET /tasks
orPOST /user
Track everything with analytics APIs
User behavior, conversion rates, feature usageSend emails with SendGrid/Mailgun
Welcome sequences, password resets, marketing campaigns
API Design & Best Practices
RESTful API Conventions
When building your own APIs, follow these patterns:
- GET
/users
— retrieve all users - GET
/users/123
— retrieve specific user - POST
/users
— create new user - PUT
/users/123
— update user - DELETE
/users/123
— delete user
Error Handling
Your API should return meaningful error codes:
{
"error": "User not found",
"code": 404,
"message": "No user exists with ID 123"
}
API Documentation
Always document your APIs using tools like: - Swagger/OpenAPI — interactive documentation - Postman Collections — shareable API examples - ReadMe — beautiful documentation sites
Security & Privacy Best Practices
Secret Key Management
- Never hardcode API keys — use environment variables (.env files)
- Rotate keys regularly — especially if compromised
- Use different keys for different environments — dev, staging, production
- Store secrets securely — use services like AWS Secrets Manager, HashiCorp Vault
- Add .env to .gitignore — never commit secrets to version control
Privacy & Data Protection
- Minimize data collection — only request what you actually need
- Encrypt data in transit — always use HTTPS/TLS
- Encrypt sensitive data at rest — especially user data, payment info
- Implement proper access controls — not everyone needs admin API keys
- Log carefully — never log API keys, passwords, or sensitive user data
- GDPR/CCPA compliance — understand data retention and deletion requirements
API Communication Security
- Use HTTPS always — never send keys over HTTP
- Validate all inputs — prevent injection attacks
- Implement rate limiting — protect against abuse and DDoS
- Use API versioning — maintain backward compatibility
- Monitor API usage — detect unusual patterns or potential breaches
When Things Go Wrong
- Have an incident response plan — what to do if keys are compromised
- Monitor for leaked secrets — tools like GitGuardian can scan your repos
- Audit API access regularly — who has access to what keys
- Document your security practices — for compliance and team onboarding
A leaked Stripe key means unauthorized charges. A compromised OpenAI key means someone burns through your AI budget. Poor privacy practices can lead to regulatory fines and lost user trust. Environment variable mistakes have cost founders thousands overnight.
Hands-On Exercise (Build Something Real)
Build Your First AI-Powered API
Goal: Create a simple API that summarizes text using OpenAI
Why this exercise matters: This is the exact pattern you’ll use to build AI features into your product. Master this, and you can add AI to anything.
Step 1: Set up your environment
npm init -y
npm install express openai dotenv
Step 2: Create your API
// server.js
const express = require('express');
const OpenAI = require('openai');
require('dotenv').config();
const app = express();
.use(express.json());
app
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
;
})
.post('/summarize', async (req, res) => {
apptry {
const { text } = req.body;
const completion = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [
{role: "user",
content: `Summarize this text: ${text}`
}
];
})
.json({
ressummary: completion.choices[0].message.content
;
})catch (error) {
} .status(500).json({
reserror: "Failed to summarize text",
message: error.message
;
})
};
})
.listen(3000, () => {
appconsole.log('API running on port 3000');
; })
Step 3: Test your API
curl -X POST http://localhost:3000/summarize \
-H "Content-Type: application/json" \
-d '{"text": "Your long text here..."}'
Cost & Scale Considerations
API Pricing Models
- Per request — OpenAI charges per token
- Monthly subscription — Zapier has monthly limits
- Usage tiers — Stripe charges percentage + fixed fee
When to Build vs. Buy
Build your own API when: - You need custom business logic - You want full control over data - Third-party options are too expensive
Use third-party APIs when: - The functionality already exists - It’s not core to your business - You need to move fast
Modern API Architectures
REST vs. GraphQL
REST (what we’ve covered): - Simple and widely supported - Good for CRUD operations - Easy to cache
GraphQL: - Request exactly the data you need - Single endpoint for all operations - Better for complex, nested data
Webhooks & Real-time APIs
Instead of constantly asking “is there new data?”, webhooks push data to you:
// Stripe webhook example
.post('/webhook/stripe', (req, res) => {
appconst event = req.body;
if (event.type === 'payment_intent.succeeded') {
// User paid! Update your database
console.log('Payment received:', event.data.object);
}
.json({received: true});
res; })
Why this matters:
APIs let you scale your product, connect tools, and automate workflows — without reinventing the wheel.
Using APIs well means: - Faster development — don’t rebuild what exists - Cleaner architecture — separate concerns properly - Lower engineering costs — leverage existing infrastructure - Better user experience — integrate best-in-class services
Key Takeaways for Founders
- Start with third-party APIs — build your MVP faster
- Plan for scale — understand pricing and rate limits
- Document everything — your future self will thank you
- Security first — protect your keys and user data
- Monitor and optimize — track API costs and performance
These are mission-critical skills for anyone building or launching a tech product.