Introduction to REST APIs with Flask –
Class Notes + Examples
Prepared as an academic resource
Table of Contents
Introduction
REST APIs allow applications to communicate using HTTP requests. Flask, a micro web
framework in Python, is ideal for building RESTful APIs.
Learning Objectives
- Understand what REST means
- Create routes with Flask
- Handle GET and POST requests
Key Concepts
REST (Representational State Transfer) is based on stateless communication. Flask uses
decorators to define API routes.
Example Code
from flask import Flask, jsonify, request
app = Flask(__name__)
books = [{"id": 1, "title": "1984"}]
@app.route("/books", methods=["GET"])
def get_books():
return jsonify(books)
@app.route("/books", methods=["POST"])
def add_book():
book = request.get_json()
books.append(book)
return jsonify(book), 201
if __name__ == "__main__":
app.run(debug=True)
Summary
With just a few lines of code, Flask can be used to serve data via a REST API. It’s great for
lightweight web applications.
Review Questions
- What are the key principles of REST?
- How does Flask handle routes?
- How do you receive JSON data in Flask?