Dev.to AI 🤖 Ai 👁 0 📖 16 min read

What are APIs? And How Do They Work?

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

What are APIs? And How Do They Work?

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.

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 in order to deliver the experiences we expect from them.

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 API connects all these systems instead of them working alone.

I like to think of APIs as something that makes building things easier. I have a friend, she is an AgriTech expert, and I am not. Whenever I'm working on something that needs that AgriTech expertise, I call her. That's an API. I don't have to worry about AgriTech, I just call her and ask her what I need.

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. 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

So, we've established that APIs help software communicate. But here's the thing: not every conversation happens the same way.

Imagine you're building an application. Sometimes you need to fetch a user's profile. Sometimes you need to retrieve very specific information from a database. And sometimes, you need to receive updates the instant something happens.

One approach won't necessarily be the best fit for every situation. Let's meet four technologies you're likely to encounter.

1. REST: The Reliable One

Imagine ordering something online. You request a product, the system retrieves its details, and you get a response. Later, you might send another request to update your profile or delete an item.

This is the kind of interaction REST APIs commonly support.

REST (Representational State Transfer) is used to design APIs, particularly web APIs that work over HTTP. It commonly organises information into resources, such as users, products, and blog posts, which clients can access through URLs.

Remember our JSONPlaceholder example? We sent a GET request to retrieve a post. That was an example of using a REST API.

REST is popular because it provides a familiar approach to building web services that different applications can consume.

When would you use it? When building a typical web or mobile application that needs to retrieve, create, update, or delete resources.

2. SOAP: The Rule Follower

If REST is the flexible colleague, SOAP is the one who follows the procedure to the letter.

Simple Object Access Protocol (SOAP) is a messaging protocol that defines rules for exchanging structured messages, commonly using XML.

It comes with a more formal messaging structure than the typical REST API. SOAP also supports standards for concerns such as security and reliable messaging, which can be important in enterprise environments.

You'll encounter it in systems that depend on established SOAP-based integrations, including some financial and enterprise services.

When would you use it? When integrating with a system that requires SOAP or relies on its established messaging standards. You wouldn't normally choose it just because you want to build a simple beginner project.

3. GraphQL: The Specific One

Imagine asking someone to bring you everything in their fridge when all you wanted was a bottle of water.

That's what requesting unnecessary data can feel like.

GraphQL gives clients a way to request specific fields from an API, within the schema and permissions the server provides.

For example, suppose you're building a profile page. You need a user's name and email address, but the API can also provide their biography, posts, preferences, and other information.

With GraphQL, you can request just the fields your page needs.

This can be especially useful when different screens require different combinations of data. However, whether it improves performance depends on how the API and its queries are designed.

When would you use it? When your application needs flexible data retrieval, particularly when multiple clients or screens need different views of the same underlying data.

Want to see what these queries actually look like? Explore the official GraphQL introduction

4. WebSockets: The One That Never Stops Talking

Most of our examples so far have followed a familiar pattern: send a request, receive a response, and move on.

But what happens when you need information to keep flowing?

Imagine a multiplayer game. You wouldn't want to keep asking the server whether another player has moved. You want updates as the game progresses.

WebSockets enable two-way communication between a client and a server over an established connection. Either side can send messages without waiting for a new request to initiate each exchange.

This makes WebSockets useful for applications such as live chat, multiplayer games, and real-time dashboards.

When would you use them? When your application needs frequent, low-latency updates or ongoing two-way communication.

Quick comparison

These aren't all the same kind of thing. Here's a quick comparison.

Technology Its main strength Example use case
REST Resource-oriented web APIs Retrieving product information
SOAP Structured messaging with established standards Integrating with a SOAP-based enterprise system
GraphQL Requesting specific fields Fetching the data needed for a complex dashboard
WebSockets Ongoing, two-way communication Live chat or multiplayer gaming

Before we move on, there's an important distinction to understand: these four aren't all the same kind of technology.

REST is an architectural style, SOAP is a messaging protocol, GraphQL is a query language and runtime, and WebSocket is a communication protocol that can support real-time applications.

They also aren't necessarily mutually exclusive. One application could use REST to retrieve ordinary resources, GraphQL for flexible queries, and WebSockets for live notifications.

The best choice depends on the problem you're trying to solve. You don't need WebSockets for a simple weather app, just as you don't necessarily need GraphQL to retrieve a single blog post.

Choose the technology that fits the job, not the one that sounds the most impressive.

Why APIs Matter (and Where They Can Hurt)

APIs make it possible to build on existing technology instead of reinventing the wheel. They let developers combine different services into applications that would be far more complicated to create from scratch.

And if you're into AI like I am, this becomes even more interesting. Imagine building an AI-powered application that sends prompts to a language model, retrieves relevant information from a database, and processes payments through a payment provider. APIs can help connect these separate services into one application.

It's worth remembering, though, that an AI model and an AI API aren't the same thing. The model performs the inference, while an API can provide an interface for sending input to a hosted model and receiving its output. This means developers can build AI-powered applications without necessarily hosting the model themselves.

Sounds convenient, right? Well, there's a catch.

The catch: You're relying on someone else's system.

When you integrate an external API, you're also taking on some of its limitations.

  • Rate limits: The provider may restrict how many requests you can make within a given period.

  • Costs: Some services charge based on usage, so a popular application can generate a surprisingly large bill.

  • Security: Poorly protected credentials can expose your account or allow someone else to use your API access.

  • Reliability: Network problems, server outages, or failed requests can affect your application.

  • Breaking changes: Providers can change their APIs, forcing you to update your code to maintain compatibility.

There's also dependency risk. An external API might become unavailable, introduce new restrictions, or discontinue a feature your application relies on.

The solution isn't to avoid APIs. It's to use them thoughtfully. Protect your credentials, understand the provider's terms and limits, handle errors gracefully, and avoid assuming that an external service will always be available.

APIs make building software easier, but they don't eliminate the responsibility of building it well.

If you'd like to explore API security in more depth, the OWASP API Security Project is a useful starting point.

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, so your experience may vary. Before starting, check each provider's current documentation for API keys, account requirements, usage limits, and pricing.

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 expose private API keys in frontend code or commit them to GitHub. For a web application, send authenticated requests through your backend and load credentials securely from environment variables.

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. You don't need to understand every internal detail of a server to use an API. You do need to understand how to make a valid request, interpret the response, and handle errors.

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

An API is an interface that defines how software components interact. An API key is a credential that some providers use to identify a client or project and enforce usage limits. Depending on the service, it may also be associated with billing.

Think of the API as the rules for accessing a service and the API key as a credential used to gain access.

Is a free API really free?

Sometimes, but free access often comes with conditions. Providers may impose rate limits, restrict commercial use, or charge for additional usage. Always check the documentation and pricing before building an application that depends on a service.

Conclusion

An API (Application Programming Interface) defines how software components interact without needing to know each other's internal workings. Think of it like ordering from a restaurant menu: you make a request without needing to know everything happening in the kitchen.

With web APIs, applications commonly communicate through requests and responses. We saw this in practice using Python's requests library to retrieve data from another service.

We also explored different approaches to building APIs, including REST, SOAP, GraphQL, and WebSockets, along with their benefits and trade-offs.

APIs make integration easier, but they also introduce considerations such as authentication, rate limits, costs, security, and reliability.

The best way to understand APIs is to use them. Start with a small project, experiment with requests, deliberately test what happens when things go wrong, and learn from the results.

The next time you use an application, you might find yourself wondering which APIs are working behind the scenes.

Happy coding, and 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/

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.