What Are APIs? And How Do They Work?

What Are APIs? And How Do They Work?

●1 ●2 ●19
calendar_today • schedule12 min read
— Originally published at dev.to

A beginner-friendly guide, with a bit of Python and a lot of food analogies.

Imagine you're building a weather application, and it needs to show the current temperature in Mutare. There's just one problem: you don't own any weather sensors, and you definitely don't have a meteorological database lying around. Building that infrastructure yourself would be a huge project. Why reinvent the wheel? So you borrow the data from a service that already has it.

The tool that makes this possible is something developers use all the time, often without noticing: an API.

Welcome to another article, where we talk about APIs. Why they're needed, what they are, how they work, types of APIs, and show an example of a code block using an API.

In simple terms, an API is a defined interface that lets one piece of software interact with another. If you like, think of APIs as the cellphones of applications: they give programs a set way to call each other up and ask for things, like: "Hey, can I have all the PDF documents on machine learning for beginners?"

In this article, we'll cover what APIs are, how they work, how to make your first API request in Python, the main types you'll hear about, and five beginner projects to practise on.

Why Do Applications Need to Communicate?

Modern applications rarely work alone. They depend on data and services provided by other systems.

Take a food delivery app. It needs restaurant menus, a payment service, a map to show your location, and live tracking so you can follow your food as it's being delivered. Each job belongs to a different system, and the app connects to them instead of building everything itself.

The same is true for AI applications. A chatbot might send a prompt to an AI model through one API, then fetch relevant information from a database through another, and combine both to write its answer. Each part has one responsibility, and each is reached through its own interface.

Now let's bring this closer to home. In my current capstone project, we have five group members, each with different roles and strengths. We can't just disappear into our corners and hope everything magically fits together at the end. We need agreed rules: who builds what, what each piece takes in, and what it hands back.

Software components need the same thing. Without a clearly defined way to talk to each other, they can't reliably work together. That defined way of making requests and passing information is the API.

What Is an API?

Six months ago, I didn't even know what the letters stood for. Today I can tell you that API stands for Application Programming Interface.

Here's the more precise definition. An API is a defined interface that allows one software component to interact with another. It specifies how requests can be made, what information or functionality is available, and how the receiving system communicates the result (Amazon Web Services, n.d.).

The application using the API doesn't need to know all the internal details of the system providing the service. It needs to understand the interface and follow the rules for using it.

The restaurant menu analogy

Think of a restaurant menu. It tells you what you can order and what to expect back: "Quarter chicken and chips with lettuce", and sometimes even a picture of the plate you're about to get.

You don't need to know how the kitchen works, where the ingredients are stored, or what the chef does behind the scenes. You look at the menu and place your order. That's it.

In this analogy, the menu is the API (the interface), and your order is the request. It's basically: "I want this. I don't need to know how you do it, but here's how I'll ask for it."

A quick caveat, though. The menu doesn't cook anything. In a typical web API, the API defines the interaction, while the server behind it does the actual work. Keep that in mind, because we'll come back to it.

APIs aren't only for the internet

Note: An API isn't necessarily a website, a database, or something that runs over the internet. APIs also exist inside programs. For example, a software library has an API that tells you which functions you can call, and an operating system has APIs that let programs open files or draw things on screen.

How Do APIs Work? The Request-Response Cycle

Let's put the restaurant to work. You're hungry and you order a burger:

  1. You place an order (request). Your application asks for something, like the current weather in Mutare.
  2. The kitchen gets to work (processing). The server receives the request and prepares what was asked for.
  3. Your food arrives (response). The server sends the result back, and your application displays it.

Here's how the roles line up:

  • The menu is the interface and its rules.
  • The customer is the client (your application).
  • The kitchen is the server that processes the request.
  • The meal is the response.

In a typical web API interaction, the client sends a request to an endpoint (a specific web address) using a defined format and method. The server receives the request, validates it, and performs the required operation, which may involve retrieving data or communicating with another service. It then returns a response, often containing a status code and data formatted as JSON (MDN Web Docs, n.d.).

What happens when something goes wrong?

Not every order ends with a delicious burger. You might order something that isn't on the menu (an invalid request), the kitchen might run out of ingredients (a server error), or the waiter might never make it to your table (a network problem). If something goes wrong, the server may return an error response instead, and the client should be ready to handle both successes and failures.

Making Your First API Request in Python

Enough theory. Let's actually use an API!

We'll use Python and JSONPlaceholder, a free fake online REST API built for testing and experimentation. It lets us practise a simple request without building our own backend.

First, install the requests library:

pip install requests

Next, the code:

import requests

url = "https://jsonplaceholder.typicode.com/posts/1"

try:
    response = requests.get(url, timeout=10)
    response.raise_for_status()
    post = response.json()
    print(f"User ID: {post['userId']}")
    print(f"ID: {post['id']}")
    print(f"Post Title: {post['title']}")
    print(f"Post Body: {post['body']}")
except ValueError:
    print("The response was not valid JSON.")
except requests.RequestException as error:
    print("Request failed:", error)

That's it, we've just made an API request! Here's what's happening, in plain language:

  • requests.get(url, timeout=10) sends an HTTP GET request, which means "please give me this." It's us placing our order. The timeout=10 tells Python to stop waiting after 10 seconds, so our program doesn't hang forever if the kitchen has vanished.
  • response.raise_for_status() checks whether the request succeeded. If the server answers with an error status code (like 404 for "not found" or 500 for "server problem"), it raises an exception instead of letting the program carry on as if nothing happened (Requests, n.d.).
  • response.json() parses the response body, which means it turns the JSON text into Python data (here, a dictionary) that we can work with. If the body isn't valid JSON, this step fails.
  • post['userId'], post['id'], post['title'] and post['body'] each read one field from that dictionary: who wrote the post, the post's own number, its title and its text. The f-strings add a label in front of each value so the output is easy to read.
  • The except blocks are our safety net. One catches invalid JSON, and the other catches request failures such as timeouts, connection problems and bad status codes. Either way, we print a readable message instead of crashing.

Here's what I got when I ran the code:

The API returns a sample post with a user ID, a post ID, a title and a body, and those are the four values we printed. We don't know how the service stores that data, and we don't need to. We use the interface and work with what comes back.

Tip: Run this code yourself and then break it on purpose. Change the URL to /posts/99999 or remove a letter from the address, and watch which error message appears. You'll learn more from the failures than from the success.

Types of APIs: REST, SOAP, GraphQL and WebSockets

Do all APIs work the same way? The short answer is no. Here are four you'll hear about often.

REST APIs

REST is an architectural style commonly used to build web APIs, often over HTTP. Resources like users, products or blog posts are accessed through addresses. Our JSONPlaceholder example was a REST API.

Use it when: you're building a standard web or mobile backend. It's a sensible starting point for most beginners.

SOAP APIs

SOAP is a messaging protocol that exchanges structured messages, usually written in XML, under strict rules. It's more rigid than REST and is often found in older or enterprise systems.

Use it when: you're integrating with a system that already requires it, such as some banking or enterprise services.

GraphQL APIs

GraphQL is a query language and runtime. Clients can request the specific fields they need, within the limits of the server's schema and permissions. An app showing a profile page might ask only for a user's name and email instead of their entire record.

Use it when: different screens or clients need different slices of the same data.

Further reading: The official GraphQL introduction explains queries and schemas.

WebSocket APIs

WebSockets provide a persistent, two-way connection, instead of the usual "ask once, answer once" pattern of HTTP. They can support real-time APIs.

Use it when: you need constant live updates, such as chat, multiplayer games or live dashboards.

These aren't all the same kind of thing

Here's the part that confused me at first: these four aren't competing options from the same category. REST is an architectural style, SOAP is a protocol, GraphQL is a query language and runtime, and WebSocket is a communication protocol. They also aren't mutually exclusive. A single application might use REST for normal data, GraphQL for flexible queries and WebSockets for live notifications.

There's no single API style that fits every situation. The right choice depends on what you're building.

Why APIs Matter (and Where They Can Hurt)

APIs let developers build on existing technology, combining services into applications that would be far more complicated to create alone.

If you're into AI like I am, this matters even more. Picture an AI-powered application that uses a language model, retrieves information from a database and processes payments, all through separate APIs.

An AI model and an AI API are not the same thing. The model performs the inference, while an API can provide a defined way for an application to send input to a hosted model and receive its output. This means developers can build AI-powered applications without necessarily hosting the model themselves, although they still need to manage the surrounding application logic, security and usage costs.

The trade-offs of depending on someone else's API

Although APIs make integration easier, they also introduce considerations such as authentication, rate limits, security and reliability. Some services require API keys, while others restrict the number of requests a client can make or charge based on usage. Requests can also fail because of network issues or server errors. Developers should protect private credentials, follow the provider's usage requirements, and design applications to handle failures gracefully.

There's also dependency risk. An external API can change, go offline, impose quotas or start charging for something that used to be free. Your app is only as reliable as the services it leans on.

Further reading: The OWASP API Security Project lists the most common API security risks and how to reduce them.

5 Beginner API Projects to Practise With

Now let's practise. Each project below has a clear finish line and at least one error case to handle. The difficulty ratings are rough guides, not universal truths, so a project may feel easier or harder for you. Always check each provider's current documentation for key, account and usage requirements, since these can change.

1. Weather app (beginner)

Build an app that shows the temperature, humidity and current conditions for a place of your choice. Use Open-Meteo, which offers weather data as JSON and, at the time of writing, doesn't need an API key for its free, non-commercial use.

  • You'll practise: GET requests, query parameters, JSON responses and displaying data.
  • Success looks like: typing a city's coordinates and seeing its current weather on screen.
  • Error case to handle: the request times out or the service is unreachable.

2. Random cat image generator (beginner)

A tiny app that shows a new cat picture each time someone clicks a button. Simple, fun and surprisingly good for the basics. Use The Cat API, and check its docs for current authentication and usage requirements.

  • You'll practise: making requests, handling responses, displaying images and responding to clicks.
  • Success looks like: a new cat appears on every click.
  • Error case to handle: the image fails to load, so show a friendly message instead of a broken picture.

3. Book finder (beginner)

Let users search by title or author and show titles, authors, publication dates and cover images with the Google Books API.

  • You'll practise: search queries, query parameters, looping through multiple results and displaying structured data.
  • Success looks like: searching "Things Fall Apart" and seeing a list of matching books.
  • Error case to handle: a search that returns no results. Show "No books found" rather than a blank page.

4. Movie search app (beginner to intermediate)

Build a movie lookup that shows titles, release dates, ratings and posters using The Movie Database (TMDB) API. Check the current requirements for accounts, API keys, attribution and usage before you start.

  • You'll practise: authentication, search queries and displaying data in a user interface.
  • Success looks like: searching for a film and seeing its poster, rating and release date.
  • Error case to handle: an invalid or missing API key.

5. AI chatbot (intermediate)

Build a simple chatbot that sends a user's message to an AI model and displays the reply. Follow the OpenAI API quickstart to make your first request. Hosted model APIs need a key and may charge for usage, so keep an eye on costs.

  • You'll practise: POST requests, sending data in a request body, authentication and handling AI-generated responses.
  • Success looks like: typing a question and getting a model-generated answer back.
  • Error case to handle: the request fails, the rate limit is hit or the key is invalid.

Warning: Never put private API keys in frontend code or commit them to GitHub. For a web app, make the API call from your server and load the key from an environment variable.

Where Should You Start?

If you've never worked with APIs before, start with the cat generator or the weather app. Both let you focus on the fundamentals without much application logic getting in the way.

Once you're comfortable, move on to the book finder and movie search. Save the chatbot for when you're ready to deal with authentication, POST requests and keeping secrets safe.

Start small, experiment, break things, and build your way up. The goal isn't only to finish the projects. It's to understand what happens each time your application talks to another service.

Frequently Asked Questions

Do I need to know how a server works to use an API?

No. That's the whole point of an interface. You need to understand how to ask and what you'll get back, not how the system works internally.

What's the difference between an API and an API key?

The API is the interface. The API key is like a membership card that some providers require so they know who is making requests and can apply limits or charges.

Is a free API really free?

Often, but usually with limits. Check the provider's documentation for rate limits, usage rules and whether free access is allowed for your kind of project.

Conclusion

An API is a defined interface that lets software components interact without needing to know each other's inner workings, much like ordering from a menu without visiting the kitchen.

In a typical web API, the client sends a request, the server processes it, and a response comes back, which might be data or an error.

We saw this in Python with requests, adding a timeout, raise_for_status() and exception handling so the code copes with failure.

REST, SOAP, GraphQL and WebSockets are different tools that can even live in the same app.

APIs make integration possible, but they bring authentication, rate limits, costs and dependency risks. Start with a small project, break it on purpose, and learn from what happens.

Now that you know what's going on behind the scenes, the next time you use an app, you might catch yourself wondering which APIs are making it work.

Happy coding!

See you next time!

References

Amazon Web Services. (n.d.). What is an API? Amazon.com. Retrieved October 14, 2026, from https://aws.amazon.com/what-is/api/

MDN Web Docs. (n.d.). HTTP. Mozilla. Retrieved October 14, 2026, from https://developer.mozilla.org/en-US/docs/Web/HTTP

Requests. (n.d.). Quickstart. Requests documentation. Retrieved October 14, 2026, from https://requests.readthedocs.io/en/latest/user/quickstart/

Want more #ai & #python deep dives?

Join 6,051+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

2 Comments

1 vote
2

More Posts

Frameworks Are Institutional Memory

Ken W. Algerverified - Sep 17

What Security Teams Want From AI Agents Before They Let Them Act Alone

Tom Smithverified - Nov 18

How AI Is Changing Web Development, and What Developers Still Need to Understand

Daniel Decker - Nov 10

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelski - Mar 19

AI Agents for Business: What They Actually Do (and 3 Ways to Use Them)

floxolab - Nov 3
chevron_left
278 Points • 22 Badges
Mutare • ruva.dev
6Posts
4Comments
7Connections
Artificial Intelligence student, developer, and technical writer interested in machine learning, dee... Show more

Related Jobs

View all jobs →

Commenters (This Week)

2 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!