pythonjsonweb-scrapingpython-requests

How to use urbandictionary API built in API function random()


I want to build a simple app that will generate random words and their associated defintion from the urban dictionary api. I was thinking I could somehow scrape the website or find a database or .csv file with most of the urban dictionary words and then inject that into the api {word}.

I found their unofficial/official API online here: http://api.urbandictionary.com/v0

And more information about it here: https://pub.dev/documentation/urbandictionary/latest/urbandictionary/OfficialUrbanDictionaryClient-class.html And here: https://pub.dev/documentation/urbandictionary/latest/urbandictionary/UrbanDictionary-class.html

Inside the second pub.dev link there appears to be a built-in function that generates a random list of words from the site. So obviously rather than having to find a database/web scrape the words this would be a much better way to create this app. Problem is I dont know how to call that function in my code.

New to APIs and here my code so far:

import requests
word = "all good in the hood"
response = requests.get(f"http://api.urbandictionary.com/v0/define?term={word}")
print(response.text)

This gives a long JSON/Dictionary in VSCODE. I think I'd be able to expand on this idea if it's possible to access that random function and just get a random word from the list.

Any help is appreciated.

Thanks


Solution

  • Scraping all the words in the Urban Dictionary would take a very long time. You can get a random word from the Urban Dictionary by calling https://api.urbandictionary.com/v0/random

    Here's a function that gets a random word from the Urban Dictionary

    def randomword():
        response = requests.get("https://api.urbandictionary.com/v0/random")
    
        return response.text
    

    In order to convert the response to JSON, you have to import JSON and do json.loads(response.text). Once converted to JSON, it is basically a dictionary. Here's a code that gets the definition, word, and author of the first definition

    data = json.loads(randomword()) #gets random and converts to JSON
    firstdef = data["list"][0] #gets first definition
    author = firstdef["author"] #author of definition
    definition = firstdef["definition"] #definition of word
    word = firstdef["word"]  #word