KAHIBARO Bookshelves
Discord Login Register

15.6. Very basic APIs

What Is an API (In Practice)?

In this chapter you’ll build very simple APIs with Python and Flask.

You’ve already seen how to create a basic web server and use routes and templates. An API (Application Programming Interface) in web development is just:

A way for programs to talk to your server and get data, usually in a structured format like JSON, instead of a full HTML page.

Key ideas for this chapter:

  • We’ll focus on HTTP APIs (often called “web APIs” or “REST-like APIs”).
  • We’ll return data, not HTML.
  • We’ll use JSON as the data format.

HTML vs JSON Responses

Until now, your Flask routes probably returned HTML strings or templates:

from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
    return render_template("index.html")

An API route usually returns JSON:

from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/api/hello")
def api_hello():
    data = {"message": "Hello from the API!"}
    return jsonify(data)
  • / might be for a human using a browser (HTML).
  • /api/hello is for another program or script (JSON).

If you open /api/hello in your browser, you’ll see something like:

{"message": "Hello from the API!"}

Returning JSON with `jsonify`

Flask has a helper called jsonify that:

  • Turns Python data into JSON.
  • Sets the correct Content-Type header (application/json).

You pass it standard Python data structures:

  • dictionaries: {"key": "value"}
  • lists: [1, 2, 3]
  • nested combinations of these

Example:

from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/api/user")
def get_user():
    user = {
        "id": 1,
        "name": "Alice",
        "is_active": True
    }
    return jsonify(user)

You can also return a list:

@app.route("/api/users")
def get_users():
    users = [
        {"id": 1, "name": "Alice"},
        {"id": 2, "name": "Bob"}
    ]
    return jsonify(users)

A Minimal API-Only Flask App

Here is a tiny app that exposes only APIs (no HTML pages):

from flask import Flask, jsonify
app = Flask(__name__)
# Simple "status" endpoint
@app.route("/api/status")
def status():
    return jsonify({"status": "ok"})
# Some dummy data
BOOKS = [
    {"id": 1, "title": "Python Basics"},
    {"id": 2, "title": "Flask for Beginners"},
]
@app.route("/api/books")
def get_books():
    return jsonify(BOOKS)
if __name__ == "__main__":
    app.run(debug=True)

Start this app and visit in your browser (or with curl):

  • http://127.0.0.1:5000/api/status
  • http://127.0.0.1:5000/api/books

You’ll see JSON responses.

Using Path Parameters

APIs often include values inside the URL, like /api/books/2.

Flask lets you capture parts of the URL as parameters:

from flask import Flask, jsonify
app = Flask(__name__)
BOOKS = [
    {"id": 1, "title": "Python Basics"},
    {"id": 2, "title": "Flask for Beginners"},
]
@app.route("/api/books/<int:book_id>")
def get_book(book_id):
    for book in BOOKS:
        if book["id"] == book_id:
            return jsonify(book)
    # Book not found
    return jsonify({"error": "Book not found"}), 404

Notes:

  • <int:book_id> means “capture this part of the path as an integer named book_id”.
  • You can return (...), 404 to set the HTTP status code to 404.

Try:

  • /api/books/1 → returns a book
  • /api/books/99 → returns an error with status 404

Using Query Parameters (`?key=value`)

Another way to pass data to an API is via query parameters, e.g.:

  • /api/search?term=python&page=2

You read them with request.args:

from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route("/api/echo")
def echo():
    # Get the 'text' query parameter: /api/echo?text=hello
    text = request.args.get("text", "")  # default to empty string
    return jsonify({"you_sent": text})

Visit:

  • /api/echo?text=hello
  • /api/echo?text=Python+is+fun

You’ll see the value you sent in the URL.

Basic HTTP Methods: GET vs POST

So far, all routes used the default GET method (usually to get data).

APIs also commonly use POST to send data to the server (e.g. creating something).

In Flask, you specify allowed methods:

from flask import Flask, jsonify, request
app = Flask(__name__)
messages = []
@app.route("/api/messages", methods=["GET"])
def list_messages():
    return jsonify(messages)
@app.route("/api/messages", methods=["POST"])
def create_message():
    text = request.form.get("text", "")
    if not text:
        return jsonify({"error": "Missing 'text'"}), 400
    message = {"id": len(messages) + 1, "text": text}
    messages.append(message)
    return jsonify(message), 201
  • GET /api/messages returns the list.
  • POST /api/messages creates a new message.

For now, you can test POSTs using tools like:

  • curl in the terminal
  • Postman or similar API tools

Example with curl (optional):

curl -X POST -F "text=Hello API" http://127.0.0.1:5000/api/messages

Sending and Receiving JSON in POST

Instead of sending form data, many APIs send JSON in the request body.

In Flask, you can access JSON data with request.get_json():

from flask import Flask, jsonify, request
app = Flask(__name__)
todos = []
@app.route("/api/todos", methods=["GET"])
def get_todos():
    return jsonify(todos)
@app.route("/api/todos", methods=["POST"])
def add_todo():
    data = request.get_json()
    if not data or "title" not in data:
        return jsonify({"error": "JSON with 'title' required"}), 400
    todo = {
        "id": len(todos) + 1,
        "title": data["title"],
        "done": False
    }
    todos.append(todo)
    return jsonify(todo), 201

Example JSON you might send:

{"title": "Learn basic APIs"}

Basic Status Codes

An API response has:

  1. Body (JSON we return)
  2. Status code (numeric HTTP code)

Common ones you’ll use:

  • 200 – OK (success)
  • 201 – Created (successfully created something new)
  • 400 – Bad Request (client sent something invalid)
  • 404 – Not Found (resource doesn’t exist)
  • 500 – Internal Server Error (server crashed / bug)

In Flask, you set the status code by returning a tuple:

return jsonify({"error": "Item not found"}), 404

Keep it simple for now: use 200 or 201 on success, 400 or 404 on basic errors.

A Tiny “Todo API” Example

Here’s a small but complete example combining everything:

from flask import Flask, jsonify, request
app = Flask(__name__)
todos = [
    {"id": 1, "title": "Learn Flask", "done": False},
]
@app.route("/api/todos", methods=["GET"])
def list_todos():
    return jsonify(todos)
@app.route("/api/todos/<int:todo_id>", methods=["GET"])
def get_todo(todo_id):
    for todo in todos:
        if todo["id"] == todo_id:
            return jsonify(todo)
    return jsonify({"error": "Todo not found"}), 404
@app.route("/api/todos", methods=["POST"])
def create_todo():
    data = request.get_json()
    if not data or "title" not in data:
        return jsonify({"error": "JSON with 'title' required"}), 400
    new_id = max([t["id"] for t in todos], default=0) + 1
    todo = {"id": new_id, "title": data["title"], "done": False}
    todos.append(todo)
    return jsonify(todo), 201
if __name__ == "__main__":
    app.run(debug=True)

This is not production-ready, but:

  • It shows GET and POST.
  • It uses path parameters.
  • It returns JSON and sets status codes.

How Another Program Could Use Your API

Imagine a Python script using your API (instead of calling functions directly). It might use the requests library like this:

import requests
response = requests.get("http://127.0.0.1:5000/api/status")
data = response.json()
print(data["status"])

You don’t need to build this script now, but it shows what APIs are for:

Your Flask app becomes a service that other programs can call.

Practice Ideas

Try adding and testing these simple API features:

  1. Add /api/time that returns the current time as JSON.
  2. Extend the books API:
    • /api/books/search?title=python – return only matching books.
  3. Add a field update route for todos:
    • e.g. /api/todos/<id>/complete that marks a todo as done (you can use POST for now).

Keep things small: a few routes, clear JSON, simple code. The goal here is to feel comfortable with:

  • Returning jsonify(...)
  • Using path and query parameters
  • Reading simple JSON from requests
  • Setting basic status codes

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms