Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Trying my hand at pulling some info from Google API, and having a bit of trouble. My code:

$body = array(
    'intitle' => 'Test', //Returns results where the text following this keyword is found in the title.
    'inauthor' => '',  //Returns results where the text following this keyword is found in the author.
    'inpublisher' => '',  //Returns results where the text following this keyword is found in the publisher.
    'key' => '', //API key
    'subject' => '', //Returns results where the text following this keyword is listed in the category list of the volume.
    'isbn' => '',  //Returns results where the text following this keyword is the ISBN number.
    'lccn' => '',  //Returns results where the text following this keyword is the Library of Congress Control Number.
    'oclc' => ''  //Returns results where the text following this keyword is the Online Computer Library Center number.
);

$args = array(
    'body' => $body,
    'timeout' => '5',
    'redirection' => '5',
    'httpversion' => '1.0',
    'blocking' => true,
    'headers' => array(),
    'cookies' => array()
);

$response = wp_remote_get( 'https://www.googleapis.com/books/v1/volumes?q=search+terms', $args );

if( is_wp_error( $response ) ) {
   $error_message = $response->get_error_message();
   echo "Something went wrong: $error_message";
} else {
   echo 'Response:<pre>';
   print_r( $response );
   echo '</pre>';
}

This consistently returns a 400 Error. If I comment out my $body array it returns perfectly (albiet without any custom parameters). Here is the error generated by Google:

Array
(
    [headers] => Array
        (
            [content-type] => text/html; charset=UTF-8
            [content-length] => 925
            [date] => Thu, 07 Feb 2013 15:09:24 GMT
            [server] => GFE/2.0
        )

    [body] => 





  Google


400. That’s an error.

Your client has issued a malformed or illegal request. That’s all we know. [response] => Array ( [code] => 400 [message] => Bad Request ) [cookies] => Array ( ) [filename] => ) 

And here is a sample when it is returned correctly:

Array
(
    [headers] => Array
        (
            [expires] => Thu, 07 Feb 2013 15:20:03 GMT
            [date] => Thu, 07 Feb 2013 15:20:03 GMT
            [cache-control] => private, max-age=0, must-revalidate, no-transform
            [etag] => "oJJnsPwmwzPHUK-6EQKPiLmyEMg/ZaxtQy3hi8hix-i3y1_kfXYZAVA"
            [content-type] => application/json; charset=UTF-8
            [x-content-type-options] => nosniff
            [x-frame-options] => SAMEORIGIN
            [x-xss-protection] => 1; mode=block
            [server] => GSE
        )

    [body] => {
 "kind": "books#volumes",
 "totalItems": 1433,
 "items": [
  {
   "kind": "books#volume",
   "id": "tskCFsTjsnkC",
   "etag": "0o/Hdha/+K0",
   "selfLink": "https://www.googleapis.com/books/v1/volumes/tskCFsTjsnkC",
   "volumeInfo": {
    "title": "The Everything Word Search Book",
    "subtitle": "Over 250 Puzzles to Keep You Entertained for Hours!",
    "authors": [
     "Charles Timmerman"
    ],
    "publisher": "Adams Media",
    "publishedDate": "2005-11-15",
    "description": "With more than 250 puzzles, 100-plus more than our competition, The Everything(r) Word Search Book provides hours of gaming fun! Searches are organized by amusing themes, including: Work Searches on the Job Global Word Searches Word Searches Alive! Word Searches for Big Bucks Decades of Word Searches to Search or Not to Search? The Everything(r) Word Search Book is sure to excite gamers of all abilities with humorous and challenging puzzles.",
    "industryIdentifiers": [
     {
      "type": "ISBN_10",
      "identifier": "1593374313"
     },
     {
      "type": "ISBN_13",
      "identifier": "9781593374310"
     }
    ],
    "pageCount": 304,
    "printType": "BOOK",
    "categories": [
     "Games"
    ],
    "averageRating": 4.0,
    "ratingsCount": 3,
    "contentVersion": "1.3.3.0.preview.3",
    "imageLinks": {
     "smallThumbnail": "http://bks0.books.google.com/books?id=tskCFsTjsnkC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
     "thumbnail": "http://bks0.books.google.com/books?id=tskCFsTjsnkC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
    },
    "language": "en",
    "previewLink": "http://books.google.com/books?id=tskCFsTjsnkC&printsec=frontcover&dq=search+terms&hl=&cd=1&source=gbs_api",
    "infoLink": "http://books.google.com/books?id=tskCFsTjsnkC&dq=search+terms&hl=&source=gbs_api",
    "canonicalVolumeLink": "http://books.google.com/books/about/The_Everything_Word_Search_Book.html?hl=&id=tskCFsTjsnkC"
   },
   "saleInfo": {
    "country": "US",
    "saleability": "FOR_SALE",
    "isEbook": true,
    "listPrice": {
     "amount": 14.95,
     "currencyCode": "USD"
    },
    "retailPrice": {
     "amount": 9.99,
     "currencyCode": "USD"
    },
    "buyLink": "http://books.google.com/books?id=tskCFsTjsnkC&dq=search+terms&hl=&buy=&source=gbs_api"
   },
   "accessInfo": {
    "country": "US",
    "viewability": "PARTIAL",
    "embeddable": true,
    "publicDomain": false,
    "textToSpeechPermission": "ALLOWED",
    "epub": {
     "isAvailable": true
    },
    "pdf": {
     "isAvailable": true.....

Thank you so much for any help you can offer.

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

I'm pretty sure you have to add the keywords or the search terms directly to the query, for example:

$key = 'flowers'; // search for word flowers in book titles.

// fill rest in as you desire
$args = array(
     'timeout' => '5',
     'redirection' => '5',
     'sslverify' => false // for localhost
);

//check for titles using +intitle
$response = wp_remote_get( 'https://www.googleapis.com/books/v1/volumes?q='. $key . '+intitle', $args );

This returns:

  "kind": "books#volumes",
     "totalItems": 795,
      //...etc etc

      'response' => 
    array
      'code' => int 200
     //etc etc..

Not sure how accurate the API is because the first book returned clearly does not have the word flowers in the title, it returns "Encyclopaedia Britannica", but I have not read the API docs.

Also for better quick debugging throw this into a plugin or your functions.php:

add_action( 'http_api_debug', 'viper_http_api_debug', 10, 5 );

function viper_http_api_debug( $response, $type, $class, $args, $url ) {
    // You can change this from error_log() to var_dump() but it can break AJAX requests
    var_dump( 'Request URL: ' . var_export( $url, true ) );
    var_dump( 'Request Args: ' . var_export( $args, true ) );
    var_dump( 'Request Response : ' . var_export( $response, true ) );
}
share|improve this answer
    
Thanks very much. It works perfectly. Now, if only I could say the same for the api... –  sosukeinu Feb 8 '13 at 4:14
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.