TypeFetched/manual/chapter-1-what-is-api.md
Casey Collier b85b9a63e2 Initial commit: TypedFetch - Zero-dependency, type-safe HTTP client
Features:
- Zero configuration, just works out of the box
- Runtime type inference and validation
- Built-in caching with W-TinyLFU algorithm
- Automatic retries with exponential backoff
- Circuit breaker for resilience
- Request deduplication
- Offline support with queue
- OpenAPI schema discovery
- Full TypeScript support with type descriptors
- Modular architecture
- Configurable for advanced use cases

Built with bun, ready for npm publishing
2025-07-20 12:35:43 -04:00

8.9 KiB

Chapter 1: What the Hell is an API Anyway?

"The best way to understand something is to see it in action. So let's start with a story..."


The Restaurant That Changed Everything

Sarah stared at her laptop screen, frustrated. Her boss had just asked her to "integrate with the weather API" for their company's new app. API? What the hell was that supposed to mean?

She took a sip of coffee and noticed something. When she'd ordered her latte, she didn't walk into the kitchen and make it herself. She didn't need to know how the espresso machine worked or where they kept the milk. She just told the barista what she wanted, and a few minutes later, she got her coffee.

That's when it clicked.

The barista was like an API.

APIs: The Waiters of the Digital World 🍽️

Let's stick with the restaurant metaphor because it's perfect:

You = Your application (the hungry customer)
The Kitchen = Someone else's server (where the data lives)
The Waiter = The API (takes your order, brings your food)
The Menu = API documentation (what you can order)
Your Order = API request (what you want)
Your Food = API response (what you get back)

You don't need to know how to cook. You don't need access to the kitchen. You just need to know how to read the menu and place an order.

// This is like walking into a restaurant
const restaurant = "https://api.weatherservice.com"

// This is like ordering from the menu
const order = "/current-weather?city=Seattle"

// This is like the waiter bringing your food
const meal = await fetch(restaurant + order)
const food = await meal.json()

console.log(food) 
// { temperature: 65, condition: "rainy", humidity: 80 }

Your First Real API Call (Yes, Right Now!)

Enough theory. Let's make an actual API call. Open your browser's console (F12) and paste this:

// Let's get a random dad joke (because why not?)
fetch('https://icanhazdadjoke.com/', {
  headers: { 'Accept': 'application/json' }
})
.then(response => response.json())
.then(data => console.log(data.joke))

Press Enter. Boom! You just made your first API call. You should see a terrible dad joke in your console.

What just happened?

  1. You sent a request to icanhazdadjoke.com
  2. You told it you wanted JSON data (not a web page)
  3. The API sent back a joke
  4. You displayed it

That's it. That's an API call. Not so scary, right?

The Language of APIs: HTTP

APIs speak a language called HTTP (HyperText Transfer Protocol). Don't let the fancy name scare you - it's just a set of rules for how computers talk to each other.

Think of HTTP like the proper etiquette at a restaurant:

The Verbs (What You Want to Do)

  • GET = "I'd like to see the menu" (reading data)
  • POST = "I'd like to place an order" (creating new data)
  • PUT = "Actually, change my order" (updating data)
  • DELETE = "Cancel my order" (removing data)

The Status Codes (What the Waiter Says Back)

  • 200 = "Here's your order!" (success)
  • 404 = "We don't have that" (not found)
  • 401 = "You need a reservation" (unauthorized)
  • 500 = "The kitchen is on fire" (server error)
// GET request - "Show me users"
fetch('https://jsonplaceholder.typicode.com/users')

// POST request - "Create a new user"
fetch('https://jsonplaceholder.typicode.com/users', {
  method: 'POST',
  body: JSON.stringify({ name: 'Sarah' }),
  headers: { 'Content-Type': 'application/json' }
})

Why APIs Matter (The Aha! Moment)

Imagine if every time you wanted weather data, you had to:

  • Buy weather monitoring equipment
  • Install it on your roof
  • Maintain it forever
  • Process all that raw data

Sounds insane, right? That's why APIs exist. Someone else (like Weather.com) has already done all that work. They expose an API that says, "Hey, just ask us for the weather, and we'll tell you."

This is the power of APIs: They let you build on top of what others have already built.

Want to:

  • Add payments to your app? Use Stripe's API
  • Send emails? Use SendGrid's API
  • Add maps? Use Google Maps API
  • Get social media data? Use Twitter's API

You're not reinventing the wheel. You're assembling a rocket ship from pre-built, tested components.

Common API Myths (Busted!)

Myth 1: "APIs are complicated"
Reality: You just made one work in 4 lines of code.

Myth 2: "I need to understand servers"
Reality: Nope. That's the server's job, not yours.

Myth 3: "APIs are just for big companies"
Reality: There are thousands of free APIs for everything from cat facts to space data.

Myth 4: "I need special tools"
Reality: Your browser can make API calls. So can any programming language.

Let's Build Something Real: Weather Checker

Time to put this knowledge to work. We'll build a simple weather checker:

<!DOCTYPE html>
<html>
<head>
    <title>Weather Buddy</title>
</head>
<body>
    <h1>Weather Buddy 🌤️</h1>
    <button onclick="getWeather()">Get Weather for Seattle</button>
    <div id="result"></div>

    <script>
    async function getWeather() {
        // Using a free weather API (no key needed for this example)
        const response = await fetch(
            'https://wttr.in/Seattle?format=%C+%t'
        )
        const weather = await response.text()
        
        document.getElementById('result').innerHTML = 
            `<h2>Current Weather: ${weather}</h2>`
    }
    </script>
</body>
</html>

Save this as weather.html and open it in your browser. Click the button. Congratulations - you just built your first API-powered application!

The Journey Ahead

Right now, you're using fetch() - the built-in way browsers make API calls. It works, but it's like driving a car with manual transmission, no power steering, and definitely no cup holders.

In the next chapter, we'll introduce TypedFetch - the luxury sports car of API calls. Same destination, but oh, what a difference in the journey.

But first, let's make sure you've got the basics down...

Practice Time! 🏋️

Exercise 1: API Explorer

Try these API calls in your browser console:

// 1. Get a random user
fetch('https://randomuser.me/api/')
  .then(r => r.json())
  .then(data => console.log(data))

// 2. Get Bitcoin price
fetch('https://api.coindesk.com/v1/bpi/currentprice.json')
  .then(r => r.json())
  .then(data => console.log(data))

// 3. Get a random quote
fetch('https://api.quotable.io/random')
  .then(r => r.json())
  .then(data => console.log(data))

Exercise 2: Status Code Detective

Visit these URLs in your browser and see the status codes:

Exercise 3: Build Your Own

Modify the Weather Buddy app to:

  1. Add an input field for any city
  2. Show temperature in both Celsius and Fahrenheit
  3. Add error handling for invalid cities

Key Takeaways 🎯

  1. APIs are just digital waiters - They take your request and bring back data
  2. HTTP is the language - GET, POST, PUT, DELETE are your vocabulary
  3. Status codes tell you what happened - 200 is good, 400s are your fault, 500s are their fault
  4. You don't need to know how APIs work internally - Just how to use them
  5. APIs let you build powerful apps quickly - Stand on the shoulders of giants

Common Pitfalls to Avoid 🚨

  1. Forgetting to handle errors - APIs can fail. Always have a plan B.
  2. Not reading the documentation - Every API is different. RTFM.
  3. Ignoring rate limits - Most APIs limit how often you can call them.
  4. Exposing API keys - Some APIs need keys. Never put them in client-side code.
  5. Expecting instant responses - Network calls take time. Plan for it.

What's Next?

You now understand what APIs are and how to use them. But let's be honest - that fetch() code is pretty verbose, error handling is a pain, and there's zero help from your editor.

In Chapter 2, we'll introduce TypedFetch - a revolutionary way to work with APIs that will make you wonder how you ever lived without it.

Get ready to turn this:

fetch('https://api.example.com/users')
  .then(response => {
    if (!response.ok) throw new Error('Network response was not ok')
    return response.json()
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error))

Into this:

const { data } = await tf.get('https://api.example.com/users')
console.log(data)

See you in Chapter 2! 🚀


Chapter Summary

  • APIs are interfaces that let applications talk to each other
  • Think of them as digital waiters in a restaurant
  • HTTP is the protocol - GET reads, POST creates, PUT updates, DELETE removes
  • Status codes tell you what happened - 200 is success, 404 is not found
  • You can make API calls with fetch() but there's a better way coming...
  • We built Weather Buddy - our first API-powered app that we'll evolve throughout this book

Next Chapter Preview: Meet TypedFetch - your new superpower for working with APIs. Zero config, maximum power.