Visualize the changes in the German gas price

If you live in Germany and want to make your own statistics about the changes in the gas price, or maybe want to integrate the gas price in your private Home Automation system display, you can do that by using the API from the website Tankerkönig.

You can get an API key and the full description of the API here. Once you have your personal API key, you can get the ID of your most favorite gas station by making an API call with the coordinates of your location and the radius to search within.

https://creativecommons.tankerkoenig.de/json/list.php?lat=52.521&lng=13.438&rad=1.5&sort=dist&type=all&apikey=YOURAPIKEY

You can just copy the call to the address bar of your browser and confirm with enter. Immediately, you should get a list of the gas stations that surround you within the given radius.

StationList

If you have found your favorite station within the list, you can use it’s unique ID to make an API call only for that particular station. I do this periodically, store the values in a RRDtool database and make graphs that show the development of the gas price during the last 24 hours and during the last seven days.

benzinpreis

benzinpreis7d

Below, you can see the Python script listed for making the API call and storing the result in a RRDtool database.

#!/usr/bin/env python

import sys
import os
import rrdtool
import urllib2
import json

try:
    # Get the gasprice for your desired gas station
    f = urllib2.urlopen('https://creativecommons.tankerkoenig.de/json/detail.php?id=DESIREDSTATIONID&apikey=YOURAPIKEY')
    json_string = f.read()
    parsed_json = json.loads(json_string)
    benzinpreis = parsed_json['station']['e5']
    f.close()
except:
    sys.exit(-1)

# Insert data into the database
data = "N:%.3f" % (benzinpreis)
rrdtool.update("%s/benzinpreis.rrd" % (os.path.dirname(os.path.abspath(__file__))), data)