Table of Contents
In this Python tutorial, learn to use an API and JSON example with Datamuse API in Python Also, I will be running Python IDLE (Python GUI) version 3.7.2.
By building a back-end API layer, this will introduce a new way of coordination between client and server code. We must consistently communicate the API endpoints to minimize any back and forth communication to be consistent and not cause confusion.
What’s an API?
API stands for Application Programming Interface and is a set of functions and procedures that allow applications to access features or data of an operating system, application, or other service that provides API access.
What’s JSON?
JSON stands for JavaScript Object Notation is a lightweight format for storing and transporting data. In addition, JSON is often used when data is sent from a server to a web page and is easy to understand.
Datamuse API Word-Finding Query
The Datamuse API is a free API that requires no sign-up or tokens for use. This API is great for developers as a word-finding query engine and is for use in your apps to find words that will match a set of constraints. Also, developers can specify a wide variety of constraints such as meaning, spelling, sound, vocabulary in the word-finding query.
Datamuse API Cheat Sheet
Note: All of the below links are set to a max of 5 with &max=5 at the end of the URL
How to find… | https://api.datamuse.com |
---|---|
words with a meaning similar to engineering big data | /words?ml=engineering+big+data |
words related to data that start with the letter i | /words?ml=data&sp=i* |
words related to python that end with the letter a | /words?ml=python&sp=*a |
words that sound like pithon | /words?sl=pithon |
words that start with d, end in a, and have two letters in between | /words?sp=d??a |
words that are spelled similarly to cali | /words?sp=california |
words that rhyme with big | /words?rel_rhy=big |
words that rhyme with coding that are related to software | /words?ml=software&rel_rhy=code |
adjectives that are often used to describe software | /words?rel_jjb=software |
adjectives describing software sorted by how related they are to code | /words?rel_jjb=software&topics=code |
nouns that are often described by the adjective tough | /words?rel_jja=tough |
words that often follow “drink” in a sentence, that start with the letter c | /words?lc=software&sp=c* |
words that are triggered by (strongly associated with) the word “code” | /words?rel_trg=code |
suggestions for the user if they have typed in softw so far | /sug?s=softw |
Table reference: https://www.digitalocean.com/community/tutorials/how-to-use-web-apis-in-python-3
Datamuse API Example
In this example we will find words with a meaning similar to engineering big data. This is a very basic example API and JSON code to print out the data that this tutorial is searching for. As one can see, there is no need for API keys or tokens in this example.
Input:
import json import urllib.request as urllib2 api_url = 'https://api.datamuse.com/words?ml=python&max=5' data = json.load(urllib2.urlopen(api_url)) def datamuse_api(): print(data) datamuse_api()
Output:
[{'word': 'monty', 'score': 57740, 'tags': ['n', 'prop']}, {'word': 'boa constrictor', 'score': 51312, 'tags': ['n']}, {'word': 'snake', 'score': 51311, 'tags': ['n']}, {'word': 'crocodile', 'score': 51310, 'tags': ['n']}, {'word': 'reptile', 'score': 51309, 'tags': ['n']}]
JSON and Python Formatting
Indent
Add an indent into the json.dumps as shown below
indent=4
Without this line all JSON text will be extracted in one line.
Input:
import json import urllib.request as urllib2 api_url = 'https://api.datamuse.com/words?ml=python&max=5' data = json.load(urllib2.urlopen(api_url)) data_format = json.dumps(data, indent=4, sort_keys=True) def datamuse_api(): print(data_format) datamuse_api()
Output:
[ { "score": 57740, "tags": [ "n", "prop" ], "word": "monty" }, { "score": 51312, "tags": [ "n" ], "word": "boa constrictor" }, { "score": 51311, "tags": [ "n" ], "word": "snake" }, { "score": 51310, "tags": [ "n" ], "word": "crocodile" }, { "score": 51309, "tags": [ "n" ], "word": "reptile" } ]
Extract and Print JSON Objects
In the below, one can pull a certain object within the list from JSON. For example, let’s only pull the ‘word’ object from the list we created with the API and json.load.
Input:
import json import urllib.request as urllib2 api_url = 'https://api.datamuse.com/words?ml=python&max=5' data = json.load(urllib2.urlopen(api_url)) data_format = json.dumps(data, indent=4, sort_keys=True) def datamuse_api(): print("Type data: ", type(data)) print("Type data_format: ", type(data_format)) print("\nPrint raw JSON data") print("\nOutput: ", data_format) def word_jason(): print("\nWords with a meaning similar to Python: ") try: for i in data: print("\t>", i['word']) except (ValueError, KeyError, TypeError): print("JSON format error") def main(): datamuse_api() word_jason() if __name__ == "__main__": main()
Output:
Type data: <class 'list'> Type data_format: <class 'str'> Print raw JSON data Output: [ { "score": 57740, "tags": [ "n", "prop" ], "word": "monty" }, { "score": 51312, "tags": [ "n" ], "word": "boa constrictor" }, { "score": 51311, "tags": [ "n" ], "word": "snake" }, { "score": 51310, "tags": [ "n" ], "word": "crocodile" }, { "score": 51309, "tags": [ "n" ], "word": "reptile" } ] Words with a meaning similar to Python: > monty > boa constrictor > snake > crocodile > reptile
I hope this API and JSON tutorial was helpful in learning the basics of API and JSON usage in Python by building a back-end API layer. By doing this, we introduced a new way of coordination between client and server code and communicated the API endpoints to minimize any back and forth communication to be consistent and not cause confusion.