Simple blog api using python flask and markdown
I have a blog generated by Hugo, and I require access to its content through a REST API. Due to Hugo’s nature as a static site generator and not a server, it lacks a native feature for exposing a REST API.
Upon further investigation, I found that I can develop a Python script using the Flask framework to create a JSON-compatible REST API for accessing my blog’s content. While it may seem unconventional to use Flask instead of generating a JSON file directly in Hugo, I view this as an opportunity to enhance my proficiency in Python.
To implement a REST API for your Hugo-generated blog using Python and Flask, you’ll need a few prerequisites. Here’s a list to guide you:
- Python: Ensure the you have python running on your system. you can download and install the lastes version of python from the official Python website
- PIP (Python package installer): verify that pip is also installed along with python.
Steps:
- create new python scripts let call it app.py
- install flask, python-frontmatter, and python-slugify
$ pip install flask
$ pip install python-frontmatter
$ pip install python-slugify
- Write the flask code
from flask import Flask, jsonify
import os
from pathlib import Path
import frontmatter
from frontmatter.default_handlers import YAMLHandler
from slugify import slugify
from json import dumps
app = Flask(__name__)
# path to article
article_path = "content/article"
def get_articles():
articles = []
for file_path in Path(article_path).rglob("*.md"):
with open(file_path, "r", encoding="utf-8") as file:
article = frontmatter.load(file, handler=YAMLHandler())
articles.append({
"title": article.get("title"),
"content": article.content,
"summary": article.get("summary", default=""),
"slug": "/%s/%s" % ("article",slugify(article.get("title")))
})
return articles
@app.route("/api/articles", methods=["GET"])
def api_articles():
articles = get_articles()
return jsonify(articles)
if __name__ == "__main__":
app.run(debug=True)
This code create a simple flask apps at /api/articles
that return blog content in json format
- Run the code
$ python app.py