Writing and Using APIs

The internet runs on APIs (Application Programming Interfaces). Whenever you check the weather on your phone, search for flights, or interact with social media, you’re using an API. But what is an API, and how do we use and create them?

In this lesson, we’ll break down how APIs work, how to use existing APIs, and how to write your own API in Python and JavaScript.


What is an API?

An API is a way for different programs to communicate with each other. APIs allow applications to request and exchange data in a structured way, often using the HTTP protocol (like websites).

Real-World API Examples:

  • Weather API: Get real-time weather data.
  • Google Maps API: Retrieve location data and directions.
  • Spotify API: Access music and playlists.

APIs usually return data in JSON format, which is easy to read and use.


Using an API

Let’s try using an API to fetch data from a website.

Example: Fetching Data from a Public API

We’ll use the JSONPlaceholder API, a free service for testing.

Python Example (Using requests):

import requests

response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
data = response.json()
print(data)

JavaScript Example (Using fetch):

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((data) => console.log(data));

Expected Output (JSON Data):

{
  "userId": 1,
  "id": 1,
  "title": "Sample Post Title",
  "body": "This is a sample post."
}

How It Works:

  1. We send a GET request to the API.
  2. The API responds with JSON data.
  3. We extract and display the data.

Writing Your Own API

APIs are not just for consuming data—we can create our own to provide data to others!

Creating a Simple API in Python (Flask)

Python’s Flask framework makes it easy to build APIs.

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/api/message")
def message():
    return jsonify({"message": "Hello, API world!"})

if __name__ == "__main__":
    app.run(debug=True)

Creating a Simple API in JavaScript (Express.js)

const express = require("express");
const app = express();

app.get("/api/message", (req, res) => {
  res.json({ message: "Hello, API world!" });
});

app.listen(3000, () => console.log("API running on port 3000"));

How It Works:

  • We define an endpoint (/api/message).
  • When a request is made, the server responds with JSON.
  • We can expand this API to handle user authentication, data storage, and more.

REST vs. GraphQL APIs

Feature REST API GraphQL API
Data Structure Predefined endpoints (/users, /posts) Clients request exactly what they need
Flexibility Fixed responses More customizable
Efficiency May return extra data Returns only requested data

Most APIs today are REST APIs, but GraphQL is gaining popularity for flexible data fetching.


Summary

APIs allow programs to communicate and exchange data.
We can fetch API data using Python’s requests or JavaScript’s fetch.
We can create APIs using Flask (Python) or Express (JavaScript).
REST APIs use structured endpoints, while GraphQL APIs provide flexible queries.

Next Steps

Try building your own API! You could:

  • Fetch data from a public API and display it.
  • Create an API that returns user profiles or messages.

What APIs have you used before? Share in the comments!

Happy coding!