jsonreactjsgoogle-apigoogle-books

Google books api returns missing parameters


I am making a react app that searches for a book by title and returns the results.

It's mostly working fine, but for some titles searched (such as "hello") it can't get the results because the parameters are missing.

Specially, the "amount" value is missing, and it can get me e-books that are not for sale even if I add the filter=paid-ebooks param while fetching the api. Using projection=full doesn't help either.

For example, when I call the api with

https://www.googleapis.com/books/v1/volumes?printType=books&filter=paid-ebooks&key=${APIKEY}

and use the fetched data inside books array in reactjs:

this.props.books.map((book, index) => {
         return (
              <CardItem
                 key={index}
                 title={book.volumeInfo.title}
                 authors={book.volumeInfo.authors ? 
                 book.volumeInfo.authors.join(', ') : 
                 "Not provided"}
                 price={book.saleInfo.listPrice.amount}
                 publisher={book.volumeInfo.publisher}
                 addToCart={() => 
                 this.props.addItem(this.props.books[index])}
                  />
                            )
                        })

One of the results it gets is like this:

"saleInfo": {
    "country": "TR",
    "saleability": "NOT_FOR_SALE",
    "isEbook": false
   }

While it should be like, what's expected is :

"saleInfo": {
    "country": "TR",
    "saleability": "FOR_SALE",
    "isEbook": true,
    "listPrice": {
     "amount": 17.23,
     "currencyCode": "TRY"
    }

And trying to search with this api answer throws the error :

TypeError: Cannot read property 'amount' of undefined

price={book.saleInfo.listPrice.amount}

As you can see in react code's authors, this issue comes up with authors parameter too, which I've bypassed as seen in the code. But I cannot do the same with amount. Is this a known error in Google Books API or is there a way to prevent this? I don't understand why it still returns me e-books that are not for sale even with filter=paid-ebooks param.


Solution

  • I have not dug into the API documentation. An ideal solution would be a query param that only sends back books with a list price (like you tried with filter=paid-ebooks). Because that's not working, a simple fix would be to filter your results once you get them.

    Assuming the response contains an array of book objects, it would look something like this:

    const paidBooks = apiResponse.data.filter(book => book.listPrice)

    This code will take the response from the API, and filter out all books that do not contain a truthy value for listPrice