I’m working with the Google Books API and I’m not so sure about the way I’m going to get the search data and return it to the user. I will describe the path here and I would like to know if you would do something different.
First, I receive a search request from the user via a form inside index.html
:
<form action='/lookup' method="post">
<input type="text" name="search" placeholder="Search by title, author, publisher, release, ISBN ...">
<button type="submit">Buscar</button>
{% block search %}{% endblock %}
</form>
So in an app.py
I get this request like this:
@app.route("/lookup", methods=["GET", "POST"])
@login_required
def search():
"""Get book search."""
if request.method == "POST":
result_check = is_provided("search")
if result_check is not None:
return result_check
search = request.form.get("search").upper()
search = lookup(search)
if search is None:
return "Invalid Search"
return render_template("search.html", search={
'totalItems': search['totalItems'],
'title': search['title'],
'authors': search['authors']
})
else:
return render_template("/")
Next, I access a lookup function in helpers.py
:
def lookup(search):
"""Look up search for books."""
# Contact API
try:
url = f'https://www.googleapis.com/books/v1/volumes?q={search}&key=MYAPIKEY'
response = requests.get(url)
response.raise_for_status()
except requests.RequestException:
return None
# Parse response
try:
search = response.json()
return {
"totalItems": int(search["totalItems"]),
"items": search["items"]
}
except (KeyError, TypeError, ValueError):
return None
To return the results to the user I have a search.html
that is still under construction:
{% extends "index.html" %}
{% block search %}
<p>Total Items: {{search['totalItems']}}</p>
<table>
<tr>
<td>
<img src="{{search['items'][0]['volumeInfo']['imageLinks']['thumbnail']}}">
<p>Título: {{search['items'][0]['volumeInfo']['title']}}</p>
<p>Autor(a): {{search['items'][0]['volumeInfo']['authors']}}</p>
</td>
<td>
<img src="{{search['items'][2]['volumeInfo']['imageLinks']['thumbnail']}}">
<p>Título: {{search['items'][2]['volumeInfo']['title']}}</p>
<p>Autor(a): {{search['items'][2]['volumeInfo']['authors']}}</p>
</td>
</tr>
</table>
{% endblock %}
Finally, my question: is this path I am following to access the API and return the data to the user the most recommended? Would you do anything other than that?