Exercise 7-a

Let’s check out some exercises that will help understand APIs with Python better.

Try to print the suggested queries below by using:

  1. Requests library
  2. params parameter
  3. DataMuse API
(Feel free to read their Documentation as you need)

Note: This exercise requires you to have your own Python setup. We recommend Anaconda Distribution as an easy and simple all-in-one solution, it’s also open source and free.

Function
Query
words with a meaning similar to steal the show
/words?ml=steal+the+show
words related to star that start with the letter c
/words?ml=star&sp=c*
words related to car that end with the letter t
/words?ml=car&sp=*t
words that start with p, end in a, and have three letters in between
/words?sp=p???a
words that rhyme with faith that are related to joy
/words?ml=faith&rel_rhy=joy
adjectives that are often used to describe sky
/words?rel_jjb=sky
adjectives describing space sorted by how related they are to future
/words?rel_jjb=space&topics=future
nouns that are often described by the adjective wild
/words?rel_jja=wild
words that often follow “heart” in a sentence, that start with the letter b
/words?lc=heart&sp=b*
words that are triggered by (strongly associated with) the word “pyramids”
/words?rel_trg=pyramids
suggestions for the user if they have typed in Zanzibar so far
/sug?s=Zanzibar

After importing requests library. You can use requests.get() to call data from the API.

If you remember the data that’s returned is requests type and if you try to print it “raw”, it will give you a code. (Some of the most common codes are 200: successful and 404: error)

To print the content in a readable way you need to try adding .text to your data.

You can experiment with params parameter. i.e.:
import requests

par_list = ["words?sp=Kentucky"]
f = "https://api.datamuse.com/words?"
data = requests.get(f, params=par_list)

print(data.text)

This exercise doesn’t have one designated solution and the goal is that you experiment with the concept until you achieve a feeling of confidence with.

Exercise 7-b

Using a loop structure and .insert method of the lists, add only the words in one of the queries that you choose to perform from above.
Once you got the data in a variable, let’s say: data1. You can loop through every item in it via a for loop.

Inside your loop you can use  .insert() method to add items to your list.

Remember to create an empty list before you start your loop

 

Inside your loop you can use  .insert() method to add items to your list.

import requests

par_list = ["words?sp=Kentucky"]
f = "https://api.datamuse.com/words?"
data = requests.get(f, params=par_list)

print(data.text)
Although this exercise doesn’t have one designated solution, you can utilize a structure similar to demonstration below:
lst = []
for i in data1.text:
    lst.insert(i[0])

print(lst)

Refresher notification: API, Requests, JSON