I'm working on a book app. I've created a database that contains book data. I ask my users which book categories they like. Let say they tell me that they like 3 categories:
1: Literature & Fiction
2: Business & Money
3: Mystery, Thriller & Suspense
To fetch books from my local database I use this query: SELECT * FROM book WHERE category IN ("Literature & Fiction","Business & Money","Mystery, Thriller & Suspense") ORDER BY RAND() LIMIT 15"
Next I created an API using Flask. Here you see the route:
@app.route('/prefered_categories/<categories>')
def prefered_categories(categories):
try:
conn = mysql.connect()
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute("SELECT * FROM book WHERE scrape_category IN %s ORDER BY RAND() LIMIT 15", categories)
row = cursor.fetchall()
resp = jsonify(row)
resp.status_code = 200
return resp
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
Running locally i tested this and got an 404: http://127.0.0.1:5000/prefered_categories/(%22Literature%20&%20Fiction%22,%22Business%20&%20Money%22,%22Mystery,%20Thriller%20&%20Suspense%22)
I'm not surprised by the 404. Because I don't know how to make this work properly. Does any of you have a solution to my problem?
UPDATE
You where right Martijn Pieters. I've updated my code with your suggestions. Currenty the code looks like this:
@app.route('/prefered_categories')
def prefered_categories():
categories = request.args['categories']
conn = mysql.connect()
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute("SELECT * FROM book WHERE scrape_category IN (%s) ORDER BY RAND() LIMIT 15", categories)
row = cursor.fetchall()
resp = jsonify(row)
resp.status_code = 200
return resp
I've also changed IN %s
to IN (%s)
and &
to %26
Now the API does work when I pas in a single category
For example http://127.0.0.1:5000/prefered_categories?categories=Romance
returns 15 books of the Romance category.
When I try http://127.0.0.1:5000/prefered_categories?categories=%22Literature%20%26%20Fiction%22,%22Business%20%26%20Money%22,%22Mystery,%20Thriller%20&%20Suspense%22
it shows a 200 request that returns []
That means that the endpoint works but the parameter that was sent in the %s
isn't recognized by MySQL so the query doesn't return any results. At least that is what I assume. Does any of you have suggestions on how to fix this?