Jump to content

  •     

Photo

Example Python Api Call

API Python

  • Please log in to reply
2 replies to this topic

#1 David Paleino

David Paleino

    Newbie

  • Members
  • Pip
  • 4 posts
  • LocationMazara del Vallo, Italy

Posted 12 November 2013 - 09:18 AM

Hello,

 

I wrote this to api@erepublik.com, but didn't receive any reply.. I would've liked this to be put on api.erepublik.com, together with the PHP version, but nevermind -- I'm posting it here :)

 

For those of you who use Python instead of PHP:

#!/usr/bin/python

from requests import session
from urllib import urlencode
from datetime import datetime
import hashlib
import hmac
import locale
from pprint import pprint
import cjson

private = ''
public = ''

def api_call(resource, action, params = None):
    locale.setlocale(locale.LC_ALL, 'C')

    with session() as s:
        date = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S')
        querystring = ''
        if params:
            querystring = urlencode(params) + ':'
        request_string = '%s:%s:%s%s' % (resource, action, querystring.lower(), date)
        print request_string
        auth = hmac.new(private, request_string, hashlib.sha256).hexdigest()

        headers = {
            'Date': date,
            'Auth': '%s/%s' % (public, auth),
        }
        print headers
        result = s.get('http://api.erepublik.com/%s/%s' % (resource, action), params=params, headers=headers)
    try:
        return cjson.decode(result.text)
    except:
        return result.text

def main():
#    result = api_call('countries', 'index')
#    result = api_call('citizen', 'profile', dict(citizenId = 1234))
#    result = api_call('country', 'regions', dict(countryId = 10))
    result = api_call('region', 'citizens', dict(regionId = 162, page = 12))
    pprint(result)

if __name__ == '__main__':
    main()

Setting the locale to C is needed for correct formatting of the date.

 

Hope it helps!


  • Mike Ontry, MaZzA and John Chorizo like this

#2 Magic

Magic

    Advanced Member

  • Members
  • PipPipPip
  • 100 posts

Posted 12 November 2013 - 02:57 PM

Huh, I honestly doubt that anyone uses Python to do such stuff, as webpages in python are rarly met nowadays(and most api calls are probably used by stats pages etc. ;)). Tho it's good to have a sample of code for it - good work :P



#3 nW0lf

nW0lf

    Newbie

  • Members
  • Pip
  • 5 posts

Posted 16 January 2015 - 06:58 AM

Nice! It kind of bugs me though that they went through all that trouble to 'secure' the API (which is pretty much just public read-only data) and so little effort in mainteining it ):


  • Jimkats1 likes this





Also tagged with one or more of these keywords: API, Python

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users