Skip to content
TORNLIFE More

Python w/Requests Install Guide

Started by tos [1976582] on in API Development.

7 replies · 2.2k views · thread synced · 3 days ago · View on torn.com
About this thread

Posts archived: 8 / 8 posts (100%) · the total is Torn's reply count + the opening post at the last fetch

Counted by TornLife from the archived posts.

Archived posts
8
Discussion span
→
People posting
6
Likes on archived posts
74
Authority score
55 / 100
Historical score
36 / 100
Story score
44 / 100
Engagement score
71 / 100

Most-liked replies

tos [1976582]

A quick guide for installing python with requests. Some basic info on how to access the Torn API after install in the posts below. Don't have a mac around so I have no idea if it works the same there. Maybe someone can post the differences.

First download and install Python 3+. For the latest version go here:

https://www.python.org/downloads/windows/

[image: i.imgur.com]

Scroll to the bottom to find the appropriate installer.

[image: i.imgur.com]

Run the installer with the following options:

[image: i.imgur.com]

[image: i.imgur.com]

[image: i.imgur.com]



Next we need to install Requests: HTTP for Humans

Open a Command Prompt window as Administrator by right clicking



[image: i.imgur.com]



Type what is on the line below into the Admin Command Prompt:

pip install requests

[image: i.imgur.com]


tos [1976582]

So I guess first step once installed... let's make a new file. Open IDLE and click new file.

[image: i.imgur.com]

[image: i.imgur.com]



This will open an editor with some nice syntax highlighting and let you push f5 to run your script.

[image: i.imgur.com]



Next I suppose let's try to access the Torn api. Hopefully you have requests working as that is what I will be using. In python what would be called an object in java script etc is called a dictionary or dict()

API link: https://api.torn.com/
Have a look around there and see what it displays.
I would recommend using the "pretty" radio buttons.

Something simple to get a result from the api and print it to the screen:

import json
import requests

apiKey = 'yourKEY'

#call to the api
APIurl = 'https://api.torn.com/user/?selections=personalstats&key=%s'%(apiKey )
getData = requests.get(APIurl)
dataAsText= getData.text
objAsDict = json.loads(dataAsText)

print(objAsDict)



You will need to use your api key to return anything other than an incorrect key error. If everything is working the above should produce the following.

[image: i.imgur.com]



What is above can be cleaned up just a little by stacking the commands for the call, the following is generally the way I start any script accessing the api. My reasoning for setting my api key as a variable at the top of any script vs leaving it in the url is for easy removal for sharing.

import json
import requests

apiKey = 'yourKEY'
APIurl = 'https://api.torn.com/user/?selections=personalstats&key=%s'%(apiKey )


obj = json.loads(requests.get(APIurl).text)

print(obj)



This will produce the same output as above, but what if we want to print just one thing instead of the whole dictionary?

We could use something like this:


print('Xanax Taken:', obj['personalstats']['xantaken'])

[image: i.imgur.com]

But then for any item in the dictionary we would have to include the ['personalstats'] portion. If only one section is being accessed/needed then you can stack that into the line where you make the api call as well:


obj = json.loads(requests.get(APIurl).text)['personalstats']

print('Xanax Taken:', obj['xantaken'])

[image: i.imgur.com]




Some Basic Looping


So far we can access the api and get its contents into a dictionary in python but in order to print it in a more human readable for we will need to loop through the dictionary.



import json
import requests

apiKey = 'yourKEY'
APIurl = 'https://api.torn.com/user/?selections=personalstats&key=%s'%(apiKey )

obj = json.loads(requests.get(APIurl).text)['personalstats']

for key in obj.keys():
print(key, obj[key])



[image: i.imgur.com]

This is obviously just a basic example, but you can play with formatting the output within the print function. If you intend to copy the output into a spreadsheet you can use 't' as a delimiter.

The print line in the loop above should hopefully be indented on your screen. In Python indentation is important! The obj.keys() part creates a list of all of the keys in the dictionary, obj is just the name I gave the variable it could be anything. Then on each iteration of the loop the variable key is the next key in the list. Again this can be named anything convenient.
tos [1976582]

So how about a script that actually does something?

import requests
import json

APIkey = 'yourKey'

#getTornItems
itemsURL = 'https://api.torn.com/torn/?selections=items&key=%s'%(APIkey)
TornItems = json.loads(requests.get(itemsURL).text)['items']

#Search for item
itemx = input("Prices on...")
itemx = itemx.title()
itemID = str()

while len(itemID) for key in TornItems.keys():
if TornItems[key]['name'] == itemx:
itemID = key
if len(itemID) itemx = input("Nope Re-Enter...")
itemx = itemx.title()

#getBazaarPrices
bazaarURL = 'http://api.torn.com/market/%s?selections=bazaar&key=%s'%(itemID,APIkey)
BazaarPrices = json.loads(requests.get(bazaarURL).text)['bazaar']

print(itemx, 'ID:', itemID)
print()
print()
#Print Prices
playerID = str()
for randID in sorted(BazaarPrices, key=lambda x: (BazaarPrices[x]['cost'], BazaarPrices[x]['quantity'])):
print(randID )
print(' Quantity:','{:,}'.format(BazaarPrices[randID ]['quantity']))
print(' Cost: ','{:,}'.format(BazaarPrices[randID ]['cost']))


print()
print()
input("Press Enter to quit...")



The while loop is checking the user's input against the full list of items from the Torn section of the api after putting the input in title case. If a match is found then the ID of that item is set as itemID. That item ID is then passed to the item market section of the api with the selection bazaar.

The ID's you see printed for bazaars are NOT player IDs or bazaar IDs or anything like that. You are not intended to be able to tell who the seller is, just the existence of the listing.

[image: i.imgur.com][image: i.imgur.com]




A Few Final Notes


All of the screen shots above were produced by pushing f5 in the editor. If you try to double click on a .py file to run it that will work but the output will flash across the screen too fast for you to read it. An easy way to make the output stay on screen long enough to be read is to put input("Press Enter to quit...") at the end of your code. This is used to get text input from the user, but we don't have to do anything with that input and it provides a simple pause. The string inside is simply the prompt to the user for what input is expected. For our purposes here it could just as well be left blank input().

Time stamps in the API are in Unix time
Python datetime reference: https://docs.python.org/3/library/datetime.html

A handy converter: https://www.epochconverter.com/

If you are having trouble running python scripts by double clicking, make sure the program set to run them is C:WINDOWSpy.exe

[image: i.imgur.com]
OCHawkeye [463691]

An example of using a class:

import requests
import json

API_KEY = 'YourKey'

class TornStocks:
"""Retrieve stock quotes from Torn API."""
def __init__(self, key):
url = 'https://api.torn.com/torn/?selections=stocks&key={}'.format(key)
r = requests.get(url)
content = r.json()

stock_json = content['stocks']
for stock in content['stocks']:
print('{},{}'.format(stock_json[stock]['acronym'], stock_json[stock]['current_price']))
setattr(self, stock_json[stock]['acronym'], stock_json[stock]['current_price'])

def quote(self, symbol):
return getattr(self, symbol)

stocks = TornStocks(API_KEY)
print(stocks.SLAG)
print(stocks.quote('SLAG'))



Keep in mind that quotes are delayed 1 hour now.