Skip to content

Instantly share code, notes, and snippets.

@nbogie
Last active June 7, 2019 23:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nbogie/b95019820ce55e10787ab09a174cb8a9 to your computer and use it in GitHub Desktop.
Save nbogie/b95019820ce55e10787ab09a174cb8a9 to your computer and use it in GitHub Desktop.
A very simple example python program to read (imagined) high scores and post high scores from/to a Web API.
# Quickstart: https://2.python-requests.org/en/master/user/quickstart/
import requests # For HTTP requests (GETting and POSTing stuff)
import random # we'll generate some random data for speed
# you can look at the scores on the server here:
# https://femi-hiscores.glitch.me/scores
# You can make your OWN server by remixing my one. Start here:
# https://glitch.com/~femi-hiscores
# server_base = "http://127.0.0.1:3001"
server_base = "https://femi-hiscores.glitch.me/"
sample_usernames = ['Grace', 'Neill', 'Nicholas', 'Nishka', 'Imran',
'Femi', 'Mutsa', 'Thomas', 'Alex', 'Oscar']
def get_scores():
URL = server_base + "/scores"
response = requests.get(url=URL)
return response.json()
def post_new_score(score, username):
URL = server_base + "/scores"
dictToPost = {'score': score, 'username': username}
response = requests.post(url=URL, json=dictToPost)
data = response.json()
return data
print("Current scores")
print(get_scores())
# WARNING: Do NOT spam my server by sending hundreds of requests, please!
# https://glitch.com/help/restrictions/
print("Posting a few random scores...")
for i in range(3):
username = random.choice(sample_usernames)
score = random.randint(1, 999)
response = post_new_score(score, username)
print(response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment