1

I'm pretty new to Python/Django but I have set up an REST API for one website (siteA.com), and would like another website (siteB.com) to be able to call this API and show some results. For this I have added the Django REST Framework and Django Auth2 Provider to siteA. I can now call the API using curl to get the access token:

curl -X POST -d "client_id=CLIENT_ID&client_secret=CLIENT_SECRET&grant_type=password&username=USERNAME&password=PASSWORD" http://www.siteA.com/oauth2/access_token   [1]

This gives the response I want:

{"access_token": "72x63615xe29f4xfdadexbcd77x27b5fx0bceexx", "scope": "read", "expires_in": 86399, "refresh_token": "5fx80dx320cx3abe7d0x27d5f1x64e7x413x0f70"}

Using the access token I get I can now call the API:

curl -v -H "Authorization: Bearer 72x63615xe29f4xfdadexbcd77x27b5fx0bceexx" "http://www.siteA.com/api/?q=SOMESTRING&per_page=3&page=1&sort=random"     [2]

Which gives me a JSON response with 3 results for the query string 'SOMESTRING'.

That all works fine, but now I wanna make these calls from within siteB.com. In other words, I want to make a page that if called with a certain seach query first checks if there's an access token like in [1], and then get the search results [2] and show them in JSON format. I just have no idea how to do it. Tried to use OAuth2 from requests_oauth2 but simply don't know the right way to translate the curl statements into Python. Any help?

Jeff
  • 820
  • 9
  • 18
  • Check out urrlib2 mate. – Odif Yltsaeb Sep 25 '13 at 16:06
  • I can see i made error in previous comment. its urllib2 not urrlib2 :P – Odif Yltsaeb Sep 26 '13 at 11:03
  • I tried it with OAUth first and failed, then tried it with Requests, but finally managed with urllib2. JUst these 3 lines do most of the work: `req = urllib2.Request(url, query_string); file = urllib2.urlopen(req); result = ast.literal_eval(file.read());` – Michael Nieuwenhuizen Sep 27 '13 at 15:31
  • `ast.literal_eval()`? `json.loads()` is more what you're after. http://stackoverflow.com/a/9949553/102260 — But seriously, use Requests — it will decode the JSON for you. `r = requests.get(url, params=query_string); r.json()` — and you're done. – Carlton Gibson Sep 27 '13 at 20:16

1 Answers1

3

If you want siteB.com to expose siteA.com's API then consider django-rest-framework-proxy (a nice third-party package).

If you want siteB.com to embed results from siteA.com's API in regular HTML pages then you'll need to hit up the API for the data and then pass that into the usual template rendering methods. As per the comment you could use urllib2 but I'd recommend the excellent Requests.

I hope that helps.

Carlton Gibson
  • 7,278
  • 2
  • 36
  • 46