Daniel Keast

Jinja template as json

programming, python

I found myself creating a mock web service for use in tests today. The idea was that during test setup I could post some json data that would then be returned during the test itself. Only a few parts of the response would change between tests, so I wanted to specify as little as possible to keep the tests descriptive.

It feels cumbersome to build the whole response as a dict in Python, and having them as flat files has the benefit that you can just leave the backend running while tweaking test data.

I’d used Jinja templates with Flask in Python before, but only for html. Turns out it’s very simple to build the response with the correct type yourself.

It’s also simple to pass in functions to be called in the template, which I’d also never done before:

app.py:

from datetime import datetime, timedelta
from flask import Flask, Response, render_template

app = Flask(__name__)

@app.route("/thing/<id>")
def get(id):
    return Response(
            render_template("thing.json",
                            id=id,
                            start=datetime.now(),
                            timedelta=timedelta),
            mimetype='application/json')

app.run(debug=True)

templates/thing.json:

{
    "thing_id": "{{id}}",
    "validFrom": "{{start}}",
    "validTo": "{{start + timedelta(days=3)}}"
}