Building RESTful APIs with Flask

Representational State Transfer (REST) is a popular architectural style for building web services. It’s based on the principles of HTTP and the principles of resource-oriented architecture. In a RESTful API, resources are represented as URLs, and the operations performed on those resources are represented by HTTP methods such as GET, POST, PUT, and DELETE.

Flask is a lightweight web framework that’s well-suited for building RESTful APIs. With Flask, you can create a RESTful API by defining a set of routes and views that correspond to the operations you want to perform on your resources.

Here’s an example of how you might create a RESTful API for articles using Flask:

from flask import Flask, request, jsonify

app = Flask(__name__)

articles = []

@app.route("/articles", methods=["GET"])
def get_articles():
    return jsonify(articles)

@app.route("/articles", methods=["POST"])
def create_article():
    data = request.json

    title = data.get("title")
    body = data.get("body")

    article = {
        "title": title,
        "body": body
    }

    articles.append(article)

    return jsonify(article), 201

@app.route("/articles/<int:id>", methods=["GET"])
def get_article(id):
    article = [a for a in articles if a["id"] == id]

    if len(article) == 0:
        return "Not found", 404

    return jsonify(article[0])

@app.route("/articles/<int:id>", methods=["PUT"])
def update_article(id):
    article = [a for a in articles if a["id"] == id]

    if len(article) == 0:
        return "Not found", 404

    article = article[0]

    data = request.json

    article["title"] = data.get("title", article["title"])
    article["body"] = data.get("body", article["body"])

    return jsonify(article), 200

@app.route("/articles/<int:id>", methods=["DELETE"])
def delete_article(id):
    article = [a for a in articles if a["id"] == id]

    if len(article) == 0:
        return "Not found", 404

    articles.remove(article[0])

    return "", 204

In this example, the articles list is used to store the articles in the API. The get_articles view is used to retrieve a list of all the articles, while the create_article view is used to create a new article. The get_article view is used to retrieve a single article by its id, while the update_article view is used to update an existing article. Finally, the delete_article view is used to delete an article.

Each view takes advantage of the jsonify function to convert the data into a JSON response. The request.json property is used to access the JSON data sent in a POST or PUT request.

It’s also important to validate the data received in a POST or PUT request to ensure that it’s in the correct format.

Here’s another example of a RESTful API with Flask, this time for managing a list of books.

from flask import Flask, request, jsonify

app = Flask(__name__)

books = []

@app.route("/books", methods=["GET"])
def get_books():
    return jsonify(books)

@app.route("/books", methods=["POST"])
def create_book():
    data = request.json

    title = data.get("title")
    author = data.get("author")
    publication_date = data.get("publication_date")

    book = {
        "title": title,
        "author": author,
        "publication_date": publication_date
    }

    books.append(book)

    return jsonify(book), 201

@app.route("/books/<int:id>", methods=["GET"])
def get_book(id):
    book = [b for b in books if b["id"] == id]

    if len(book) == 0:
        return "Not found", 404

    return jsonify(book[0])

@app.route("/books/<int:id>", methods=["PUT"])
def update_book(id):
    book = [b for b in books if b["id"] == id]

    if len(book) == 0:
        return "Not found", 404

    book = book[0]

    data = request.json

    book["title"] = data.get("title", book["title"])
    book["author"] = data.get("author", book["author"])
    book["publication_date"] = data.get("publication_date", book["publication_date"])

    return jsonify(book), 200

@app.route("/books/<int:id>", methods=["DELETE"])
def delete_book(id):
    book = [b for b in books if b["id"] == id]

    if len(book) == 0:
        return "Not found", 404

    books.remove(book[0])

    return "", 204

In this example, the books list is used to store the books in the API. The get_books view is used to retrieve a list of all the books, while the create_book view is used to create a new book. The get_book view is used to retrieve a single book by its id, while the update_book view is used to update an existing book. Finally, the delete_book view is used to delete a book.

Each view takes advantage of the jsonify function to convert the data into a JSON response. The request.json property is used to access the JSON data sent in a POST or PUT request.