简体   繁体   中英

API call from one Django site to another

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM