Lab: Web APIs and JSON-LD

Revision as of 09:41, 17 April 2020 by Say004 (talk | contribs)




We will use Web APIs to retrieve regular JSON data, and then append it with a semantic context (@context). Finally we will parse it with RDFlib.


  • import requests
  • import json
  • import pprint
  • from rdflib import Graph


Regular JSON web APIs


The GeoNames web API ( offers many services. For example, you can use this URL to access more information about Ines' neighbourhood in Valencia: (You might need to register a username instead of using "demo"). ' You can register here if you want to:

You do not have to use the GeoNames web API. There are lots and lots of other web APIs out there. But we preferably want something simple that does not require extensive registration (HTTPS can also make things more complex when the certificates are outdated). Here are some examples to get you started if you want to try out other APIs: , , , /intro , .



Lifting JSON to JSON-LD

In python we can represent JSON objects as dictionaries ({}) and JSON Arrays as lists ([]).

So far we have only used plain JSON. Now we want to move to JSON-LD, the semantic version of JSON. Make a new JSON object (dictionary/{} in python) called context. Put a single entry into this map, with "@context" as the key and another object ({}) as the value. It is this second map that contains the actual mappings.




Go back to the RDF/RDFS programs your wrote in labs 2 and 3 if you can. Extend the program so that it adds further information about the post codes of every person in your graph.

We will now make a RDFlib Graph from the JSON-LD object.

First you need to pip install the json-ld portion of rdflib if you have not already:

pip install rdflib-jsonld

Now, create a new Graph. Then convert the JSON-LD object to a string (use json.dumps() and write it to a file). Then parse the file with Rdflib (g.parse()).

Congratulations - you have now gone through the steps of accessing a web API over the net, lifting the results using JSON-LD, manipulating the in JSON-LD and reading them into a RDF Graph. Of course, it is easy to convert the RDFlib graph back into JSON-LD using g.serialize("json-ld")

If You have more time

Useful Reading

- Reading and writing with JSON -