2

https://www.goodreads.com/api/index contains an example how to call json api by js

           <script type="text/javascript">
            function myCallback(result) {
              alert('nb of reviews for book: ' + result.reviews.length);
            }
            var scriptTag = document.createElement('script');
            scriptTag.src = "https://www.goodreads.com/book/isbn/0441172717?callback=myCallback&format=json&user_id=123456789";
            document.getElementsByTagName('head')[0].appendChild(scriptTag);
            </script>

To be frank, it is so strange to me that url could contains a callback function name. What's the secret here? Any relevant js document?

Anyway, it is a javascript example. If I want to use python requests to do the same job. How and what should I do?

I am completely stuck here.

Thanks for your advice.

new2cpp
  • 3,311
  • 5
  • 28
  • 39

1 Answers1

2

This type of call is really only used from the browser, so it wouldn't apply to a Python request.

This is an example of a JSONP request, which is a way to make a cross-origin request, EG, your app served at foobar.com wants to make a POST request to example.com. In many (but not all) circumstances such requests will be blocked by your browser for security reasons.

In this case, the result of the request is passed to the callback, which is then executed by the browser.

Related questions have been asked before, there's a nice explanation of JSONP-- how it works, and why you would want use it here: https://stackoverflow.com/a/2067584/3084820

If you are using requests you won't have the cross-origin concern, since you'll be making that request from the server side. I am not familiar with the goodreads API but I suspect that they have a version of the endpoint that can be called from a server.

NOTE: The Goodreads API is fairly weird and not well-documented. I played around with this and was able to get it to work using requests, but EG you need to send your API key as key=... not user_id=...

Matt Morgan
  • 4,900
  • 4
  • 21
  • 30
  • learned new knowledge `JSONP`, thanks so much. Though never used before and hopefully don't need to use in futuer. BTW, if you pass `key`, it will work and only return `xml`. If you pass `user_id` for `json`, it only works for browser but not from python request – new2cpp Dec 16 '18 at 14:15