Python w/Requests Install Guide | API Development | TORN

Python w/Requests Install Guide

​

    • tos [1976582]
    • Role: Civilian
    • Level: 100
    • Posts: 525
    • Karma: 994
    • Last Action: 1 month
      • 0
    • Reason:
      Are you sure you want to report this post to staff?
      Cancel
    Thread created on 20:59:36 - 09/03/17 (9 years ago)
    |
    Last replied 02:51:19 - 05/04/17 (9 years ago)
    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/



    Scroll to the bottom to find the appropriate installer.



    Run the installer with the following options:









    Next we need to install Requests: HTTP for Humans

    Open a Command Prompt window as Administrator by right clicking







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

    pip install requests

    • tos [1976582]
    • Role: Civilian
    • Level: 100
    • Posts: 525
    • Karma: 994
    • Last Action: 1 month
      • 0
    • Reason:
      Are you sure you want to report this post to staff?
      Cancel
    Posted on 20:59:54 - 09/03/17 (9 years ago)
    Post link copied to clipboard Copy post link
    So I guess first step once installed... let's make a new file. Open IDLE and click new file.







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





    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.





    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'])


    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'])






    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])





    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.
    Last edited by tos on 01:52:48 - 11/03/17 (9 years ago)
    • tos [1976582]
    • Role: Civilian
    • Level: 100
    • Posts: 525
    • Karma: 994
    • Last Action: 1 month
      • 0
    • Reason:
      Are you sure you want to report this post to staff?
      Cancel
    Posted on 21:00:13 - 09/03/17 (9 years ago)
    Post link copied to clipboard Copy post link
    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.






    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
    If you are having trouble running python scripts by double clicking, make sure the program set to run them is C:WINDOWSpy.exe

    Last edited by tos on 18:37:43 - 20/01/18 (8 years ago)
    • saeed [1826888]
    • Role: Civilian
    • Level: 100
    • Posts: 1,049
    • Karma: 748
    • Last Action: 5 months
      • 0
    • Reason:
      Are you sure you want to report this post to staff?
      Cancel
    Posted on 21:13:21 - 09/03/17 (9 years ago)
    Post link copied to clipboard Copy post link
    r+
    • 1by1takeyoudown [744502]
    • Role: Civilian
    • Level: 83
    • Posts: 3,319
    • Karma: 392
    • Last Action: 2 hours
      • 0
    • Reason:
      Are you sure you want to report this post to staff?
      Cancel
    Posted on 01:53:57 - 14/03/17 (9 years ago)
    Post link copied to clipboard Copy post link
    nice, thank you for this.

    Now that i'm older, i thought it was great that i seemed to have more patience.

    turns out i just don't give a shit anymore.
    • Swatsicle [1593313]
    • Role: Civilian
    • Level: 100
    • Posts: 6,094
    • Karma: 9,111
    • Last Action: 3 hours
      • 0
    • Reason:
      Are you sure you want to report this post to staff?
      Cancel
    Posted on 15:05:22 - 14/03/17 (9 years ago)
    Post link copied to clipboard Copy post link
    Shit, sweet guide! :)

     

    • Insurgency [2020585]
    • Role: Civilian
    • Level: 44
    • Posts: 235
    • Karma: 29
    • Last Action: 7 years
      • 0
    • Reason:
      Are you sure you want to report this post to staff?
      Cancel
    Posted on 16:21:50 - 15/03/17 (9 years ago)
    Post link copied to clipboard Copy post link
    think i might actually be able to learn something from this xD r+

    • OCHawkeye [463691]
    • Role: Civilian
    • Level: 72
    • Posts: 62
    • Karma: 5
    • Last Action: 5 years
      • 0
    • Reason:
      Are you sure you want to report this post to staff?
      Cancel
    Posted on 02:51:19 - 05/04/17 (9 years ago)
    Post link copied to clipboard Copy post link
    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.
    Last edited by OCHawkeye on 20:46:40 - 05/04/17 (9 years ago)
Reply
Thread Title: