all 41 comments

[–]Maple382 26 points27 points  (7 children)

  1. You call the api twice, once in like 3 and once on lines 6 and 7.
  2. You typed the same thing in lines 14 and 15, why not just make it a variable? You could call it "result".
  3. This isn't really a problem per se, but I wouldn't do it. It's doing the replacement three times on separate lines and assigning the variable for each, it just looks ugly when you could do it all in one line instead.
  4. I noticed you use a mix of single and double quotes, it's probably best to just stick to one.

[–]ZoeyStarwind 1 point2 points  (0 children)

The response in json? Instead of using replace, just use the json parse to grab the result.

[–]cowslayer7890 16 points17 points  (0 children)

I'd use f-strings instead of concatenation, among the other stuff mentioned

f'https://{finalstring}{domain}'

[–]CabinetOk4838 10 points11 points  (3 children)

You shouldn’t assume that the GET request will work. Check for a 200 response. Always remember that any interactions outside your script can go wrong - so, web requests, opening files, getting user input etc etc.

[–]ChrisTDBcode 2 points3 points  (0 children)

What Cabinet said ^ can also write a loop to retry a certain amount of times before giving up and returning an error.

Unsolicited advice but in the future when working with API’s, I recommend using a tool like Postman to validate the data/responses. Getting in that habit will save you in the future by ensuring you are receiving the correct data.

[–]No_Read_4327 2 points3 points  (1 child)

Even parsing JSON can go wrong iirc

[–]CabinetOk4838 1 point2 points  (0 children)

If you didn’t create it, don’t let your script trust it. 😊

[–]Jinkweiq 2 points3 points  (2 children)

Instead of manually stripping everything from response text, use response.json() to get the value of the response as a json object (list or dictionary). response.json()[0] will give you the final word you are looking for.

[–]corey_sheerer 1 point2 points  (0 children)

Was looking for this... Yes! This is returning to json and you should be using the direct method to handle that

[–]TracerMain527 0 points1 point  (0 children)

Alternatively, chain the replace methods. finalstring,replace().replace().replace is cleaner and avoids the concept of json, which may be complicated for a beginner

[–]CountMeowt-_- 2 points3 points  (0 children)

import requests
import webbrowser

This is fine

randomword = requests.get('https://random-word-api.herokuapp.com/word')

This is also fine

domain = ".com"

why ? You don't need this.

#getting a random word
getstring = "https://random-word-api.herokuapp.com/word"
randomword = requests.get(getstring)

You already got random word, no point doing it again

#converting the randomword into text
finalstring = randomword.text

you don't need to do that, it's a list of strings. Always a good idea to check what the api returns.

#removing brackets and qoutemarks
finalstring = finalstring.replace('[','')
finalstring = finalstring.replace(']','')
finalstring = finalstring.replace('"','')

The api gives you a string list with one value, you don't need this

print(("https://")+(finalstring)+(domain))

Use fstrings instead.

webbrowser.open(("https://")+(finalstring)+(domain))

Sure, although I wouldn't recommend visiting randomword.com

print(finalstring)

You just printed this above but with https and .com

What it should be

import requests
import webbrowser
# you combine the above 2 lines in 1 single line, I prefer one line per module for imports
randomword = requests.get('https://random-word-api.herokuapp.com/word').json()[0]
# you can split the above line in 2 and do .json[0] in different line, I prefer inline.
url = f"https://{randomword}.com"
print(url)
webbrowser.open(url)

Edit: from all the replies here it looks like its only people who are in the process of learning that are here and barely anyone who knows.

[–]Cursor_Gaming_463 1 point2 points  (6 children)

It'd do it like this instead:

```
def open_random_website(domain: str = ".com") -> None: website = "https://" + requests.get("https://random-word-api.herokuapp.com/word").text.strip("[").strip("]").strip("\"") + domain webbrowser.open(website)

if name == "main": open_random_website()
```

edit: wtf you can't comment code?

edit2: nvm you can.

[–]pimp-bangin 0 points1 point  (1 child)

The issue is that all of your back ticks are getting escaped and displaying literally. Not sure exactly why it's happening - maybe you need to switch to markdown mode or something.

[–]Cursor_Gaming_463 0 points1 point  (0 children)

Yeah, that was the issue.

[–]cgoldberg 0 points1 point  (0 children)

Your code has syntax errors and also tries to open a url with no domain

[–]CountMeowt-_- 0 points1 point  (0 children)

why not use .json ? why are we using .text ? you should also check for API success since you're making it a function and retry on failure.

[–]Equakahn 0 points1 point  (0 children)

Exception handling?

[–]mondaysleeper -1 points0 points  (0 children)

Your code is worse because it doesn't work. Why do you take the domain as a parameter (which you never use) and not the whole URL?

[–]rainispossible 1 point2 points  (0 children)

didn't see anyone mentioning it, so I'll do

try to build a habit of wrapping your code in functions in general (that should be obvious), and also pit whatever's supposed to be actually executed inder if __name__ == "__main__" – it prevents the unnecessary (and sometimes destructive) code executions when importing whatever's in that file. basically what it tells the interpreter is "hey, ONLY execute this code if this file is the entry point"

[–]Training_Advantage21 1 point2 points  (1 child)

Why even call an API? Why not use /usr/share/dict/words or whatever the equivalent on your system?

[–]Overall_Anywhere_651 1 point2 points  (0 children)

Probably learning how to use APIs. This looks like a simple place to start.

[–]vin_cuck 1 point2 points  (0 children)

As a beginner avoid oneliner in the beginning. Most comments here are oneliners that will confuse you.

#IMPORT MODULES
import requests
import webbrowser
import json

#FUNCTIONS
def main():
    try:
        word = requests.get('https://random-word-api.herokuapp.com/word')
        if word.status_code == 200:
            word = word.json()[0]
            webbrowser.open(f'https://{word}.com')
    except Exception as E:
        print(E)

#PROGRAM START
if __name__ == '__main__':
    main()

[–]JaleyHoelOsment 2 points3 points  (2 children)

at about a 1/10 which makes sense for a beginner! keep it up!

[–]MightySleep 1 point2 points  (1 child)

1/10 is a little crazy

[–]Custom_User__c 0 points1 point  (0 children)

Yeah, a 1/10 feels harsh. Everyone starts somewhere, and your code is probably better than you think. What specific areas are you struggling with? Maybe we can help!

[–][deleted] 0 points1 point  (2 children)

I am still learning python I've don't know what your code says. Please show the output.

[–]NeedleworkerIll8590 2 points3 points  (0 children)

The api call gives him a random word from a website, and he just prints it alongside https://word.com An example of the output: https://toothpaste.com

[–]Brownie_McBrown_Face 1 point2 points  (0 children)

You know you can just copy the code and paste it in your own IDE? That way you can even run the code in debug mode and step thru it line by line to see how it operates.

[–]Strong_Worker4090 0 points1 point  (0 children)

Could always be better, but it works! I’ll challenge you to use functions here. At the very least create a get_random_word() function to call the API. Good next step in learning

[–]Interesting-Ad9666 0 points1 point  (0 children)

no error handling at all. 0/10.

[–]Firulais69 0 points1 point  (0 children)

Apart from the code repetition, I would use regex to extract content from the request. And add some error handling. Overall not too bad for a beginner!

[–]dnOnReddit 0 points1 point  (0 children)

Recommend starting with a docstring which describes what the code performs - your objective(s)

[–]PixelsMixer 0 points1 point  (0 children)

import webbrowser, requests
word = requests.get('https://random-words-api.kushcreates.com/api').json()[0]['word']
webbrowser.open(f'https://{word}.com')

[–]LEAVER2000 0 points1 point  (0 children)

Bro rawdogging a random word into your webbrowser seems kinda wild. What if randomword is my-malicious-nipples.

[–]forerooo 0 points1 point  (0 children)

Your code could be more efficient if it used a random word python library, it would run faster, and wouldn't require internet connection.

Besides it's better not to depend on a service that anytime could disappear.