Возможно, URL-адрес запроса будет примерно таким: http://localhost: 5000 / api / v1 / resource / books /? Id = 1
Для нескольких идентификаторов книг это будет примерно http://localhost: 5000 / api / v1 / resource / books /? Id = 1 & id = 2
from flask import Flask, request, jsonify
app = Flask(__name__)
books = [
{'id': 0,
'title': 'A fire Upon the Deep',
'author': 'Vernor Vinge',
'first_sentence': 'The coldsleep itself was dreamless.',
'year_published': '1992'},
{'id': 1,
'title': 'The Ones Who Walk Away From Omelas',
'author': 'Ursula K. Le Guin',
'first_sentence': 'With a clamor of bells that set the swallows soaring, the \
Festival of Summer came to the city Omelas, bright-towered by the sea.',
'published': '1973'},
{'id': 2,
'title': 'Dhalgren',
'author': 'Samuel R. Delany',
'first_sentence': 'to wound the autumnal city.',
'published': '1975'}
]
@app.route("/api/v1/resource/books/", methods=["GET"])
def api_id():
# This will look for 'id' in the url. If there's no id/ids, it will take None as default value
bids = request.args.getlist('id')
# if you are expecting to serve only one id at a time, use >> request.args.get('id')
if bids:
results = []
for book in books:
for bid in bids: # this for loop won't be required for strictly single id
if book['id'] == int(bid):
results.append(book)
return jsonify(results)
else:
return "Error: ID not provided. Please specify an ID"
if __name__ == "__main__":
app.run()
Этот код у меня работает. Надеюсь, это тоже подойдет вам.
URL-адрес запроса:
http://localhost: 5000 / api / v1 / resource / books /? Id = 0 & id = 2
Вывод:
[{"author":"Vernor Vinge","first_sentence":"The coldsleep itself was dreamless.","id":0,"title":"A fire Upon the Deep","year_published":"1992"},{"author":"Samuel R. Delany","first_sentence":"to wound the autumnal city.","id":2,"published":"1975","title":"Dhalgren"}]
URL-адрес запроса:
http://localhost: 5000 / api / v1 / resource / books /? Id = 0
Вывод:
[{"author":"Vernor Vinge","first_sentence":"The coldsleep itself was dreamless.","id":0,"title":"A fire Upon the Deep","year_published":"1992"}]
URL-адрес запроса:
http://localhost: 5000 / api / v1 / resource / books /
Вывод:
Error: ID not provided. Please specify an ID