Build Your Language Prowess with WordsAPI

RapidAPI Team
The Era of APIs
Published in
7 min readNov 26, 2019

WordsAPI, as the name suggests, is an API for the English language. It acts as a dictionary, a thesaurus, and a reference for parts of speech, related words, syllables, and more. It is a complete language guide packed into an API.

In this blog post, we will leverage this API to build a word game. Yes, A Word Game! So for all you language aficionados out there, get ready to test your English synonym skills. First, we run through a quick overview of this API and its main features. After that, we are going to create a simple word game using this API in Python.

Get Access to the WordsAPI

1. Sign Up For a RapidAPI Account

To begin using this API, you’ll first need to sign up for a free RapidAPI developer account.

RapidAPI is the world’s largest API marketplace, with over 10,000 APIs and over 1,000,000 developers. Our goal is to help developers find and connect to APIs to help them build amazing apps.

Once you sign up, you will get a single API key with which you can gain access to all our APIs.

3. Subscribe to the WordsAPI

While in the API Console, you can check out the Pricing Table under the “Pricing Tab”.

You can subscribe to the BASIC plan that gives you 2500 API calls per day.

Overview of WordsAPI

You are now all set to explore the API further.

Take a look at the API endpoints defined in the “Endpoints” tab. WordsAPI has an exhaustive collection of API endpoints for querying various information about English words.

There are two categories of endpoints. The “Related Words” category contains the endpoints for finding related words for a given word.

The “Words” category contains endpoints for getting information about a word.

Most of the endpoints are self-explanatory. However, here are some endpoints that might be of interest to you.

Dictionary

You can use this API as a dictionary. The “ GET Definitions” endpoint under the “Words” category returns the definition and the parts-of-speech category of the word.

Similar Words

The WordsAPI also supports many options to find similar words. You can check for examples of the word, find rhyming words, and more. Here is an example of finding similar rhyming words to a word. This is the “ GET Rhymes” endpoint under the “Words” category.

Related Words

Under the “Related Words” category, there are many endpoints which help you find related words in different contexts. For instance, if you want to find the related words that are more general to the given word, then you use the “ GET Is a Type Of” endpoint to return those general words.

This API also supports synonyms and antonyms. Here is how you can find synonyms of a word using the “Synonyms” endpoint under the “Words” category.

How To Use WordsAPI with Python

You will now learn how to use the Words API with Python to build a word game.

For this word game, we will use the “Synonyms” endpoint. The idea is to challenge the user to answer the right synonym for a word. The answer entered by the user is matched with the synonyms returned by the API.

Let’s take a closer look at the API response for the “ GET Synonyms” for the word ‘ lovely ‘.

The API returns four synonym words tucked inside an array pointed by the “ synonyms “ key of the JSON response.

For deciding the outcome of the game, the user’s input is matched with all the words contained in this array to decide whether the answer is right or wrong.

The Python snippet for invoking this API is available in the API Console. Choose “ Python” > “ Requests “ from the drop-down next to the “Code Snippet” section of the API console, and you should see the snippet.

Building a Synonym Word Game with the WordsAPI

Building a word game is a fun, easy way to learn more about the language. So let’s get started with the coding now. Follow along with the steps below to write a Python program for the game.

But first, you have to set up the programming environments with the requisite tools and libraries that you are going to use in this program.

Prerequisites

The program for the word game is based on the Python3 environment. You must ensure that you have

  1. Python 3 runtime environment installed on your computer
  2. Pip tool ( any recent version of pip that ships with Python 3)

Python Libraries

You also need to install a few libraries that this program depends upon.

Requests

Requests is a python library for making HTTP calls to API endpoints. It is easy to use and widely popular in the Python developer community.

To install requests, you can use the pip command.

pip install requests

RandomWords

RandomWords is an unofficial python library for generating random words.

pip install random-word

Coding the Synonym Word Game in Python

Now comes the exciting part. You are all set to build the game using Python and WordsAPI.

Before proceeding, it’s good to have an idea about the gameplay so that you understand how the program works.

Every time you run the game program, you are presented with five words, one at a time. These are the challenge words. For every challenge word, you have to type in the answer word, which, according to you, should be a synonym of the challenge word. Every correct answer earns you one point. Your final score, out of five, is displayed at the end.

Let’s write the Python program for the game. You can open your favorite editor and type in, along with the steps provided below.

Step 1: Import the Libraries

For this program, we need to import three Python modules.

  1. RandomWords library: To generate random English words.
  2. Python requests: To make API calls to WordsAPI
  3. JSON: To parse the API response.
import requests
from random_word import RandomWords
import json

Step 2: Declare Global Variables

Next up, you need a few global variables to keep a tab on the gameplay. You need to track the count of challenge words presented to the user, as well as the user’s current score. Additionally, you need a constant to limit the maximum number of words that are presented to the user.

presentation_count = 0
score_count = 0
TOTAL_PRESENTATION_COUNT = 5

You also need to declare the RapidAPI related parameters that go with the header information for invoking API calls.

headers={
"X-RapidAPI-Host": “<RAPIDAPI_HOST>”,
"X-RapidAPI-Key": “<RAPIDAPI_KEY>”

}

Make sure to replace the placeholders RAPIDAPI_HOST and RAPIDAPI_KEY with your own subscription specific values displayed in the code snippet within the API console.

Step 3: Initialize the Game

To initialize the game, you need to initialize the RandomWords library. Subsequently, a WHILE loop starts. It runs till the presentation_count reaches the value defined in the constant TOTAL_PRESENTATION_COUNT.

if __name__ == "__main__":print("WELCOME TO SYNONYM WORD GAME \n")
print("||||| LET'S PLAY ||||| \n")
r = RandomWords()while presentation_count < TOTAL_PRESENTATION_COUNT:

Step 4: API Call and Response Gathering

As per the code snippet, you saw earlier, here is how you can invoke the WordsAPI. This is defined within a separate function that gets invoked as part of the game logic.

def fetch_synonyms(word):url = "https://wordsapiv1.p.rapidapi.com/words/" + word + "/synonyms"
api_response = requests.request("GET", url, headers=headers)
return json.loads(api_response.text)

Step 5: Game Logic

The game logic starts by fetching a list of random words from the RandomWord library. For each word, the WordsAPI’s “ GET Synonyms” endpoint is called to fetch its list of synonyms. If the API returns successfully, then the word is treated as the challenge word and presented to the user.

words = r.get_random_words(hasDictionaryDef="true", includePartOfSpeech="verb", minCorpusCount=3,  minLength=3, maxLength=10, sortBy="alpha", sortOrder="asc", limit=15)for word in words:response = fetch_synonyms(word)if( 'word' in response):

if(len(response["synonyms"]) > 0):
presentation_count = presentation_count + 1

print("Enter a synonym for the word: " + word)
answer = input()

Subsequently, the user’s response is checked for a match with the list of synonyms obtained from the WordsAPI.

Based on the result of the match, the score_count is updated, and appropriate messages are displayed for the user.

match_found = Falsefor matcheval in response["synonyms"]:if(matcheval == answer):
match_found = True
score_count = score_count + 1
break
if(match_found):
print("Hurray !!! You Are Right \n")
Else:print("Bad luck, That's A Wrong Answer \n")print("Your Current Score : " + str(score_count) + "\n")if( presentation_count == TOTAL_PRESENTATION_COUNT):
break
else:
print( str(TOTAL_PRESENTATION_COUNT - presentation_count) + " More To Go \n" )

Step 6: Score Display

Finally, when the loop breaks off after reaching a value equal to the TOTAL_PRESENTATION_COUNT, the program declares that the game is over and displays the user's final score.

Continue Reading on RapidAPI

Originally published at https://rapidapi.com on November 26, 2019.

--

--