Commit 2cc8e7b5 authored by CedricPump's avatar CedricPump
Browse files

- tutorial step Connecting Our API to a Database

parent c48daf25
Pipeline #38139 passed with stages
in 1 minute and 27 seconds
import flask import flask
from flask import request, jsonify from flask import request, jsonify
import sqlite3
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config["DEBUG"] = True app.config["DEBUG"] = True
# Create some test data for our catalog in the form of a list of dictionaries. def dict_factory(cursor, row):
books = [ d = {}
{'id': 0, for idx, col in enumerate(cursor.description):
'title': 'A Fire Upon the Deep', d[col[0]] = row[idx]
'author': 'Vernor Vinge', return d
'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('/', methods=['GET']) @app.route('/', methods=['GET'])
...@@ -32,30 +20,51 @@ def home(): ...@@ -32,30 +20,51 @@ def home():
@app.route('/api/v1/resources/books/all', methods=['GET']) @app.route('/api/v1/resources/books/all', methods=['GET'])
def api_all(): def api_all():
return jsonify(books) conn = sqlite3.connect('books.db')
conn.row_factory = dict_factory
cur = conn.cursor()
all_books = cur.execute('SELECT * FROM books;').fetchall()
return jsonify(all_books)
def page_not_found(e):
return "<h1>404</h1><p>The resource could not be found.</p>", 404
@app.route('/api/v1/resources/books', methods=['GET']) @app.route('/api/v1/resources/books', methods=['GET'])
def api_id(): def api_filter():
# Check if an ID was provided as part of the URL. query_parameters = request.args
# If ID is provided, assign it to a variable.
# If no ID is provided, display an error in the browser. id = query_parameters.get('id')
if 'id' in request.args: published = query_parameters.get('published')
id = int(request.args['id']) author = query_parameters.get('author')
return "Error: No id field provided. Please specify an id." query = "SELECT * FROM books WHERE"
to_filter = []
# Create an empty list for our results
results = [] if id:
query += ' id=? AND'
# Loop through the data and match results that fit the requested ID. to_filter.append(id)
# IDs are unique, but other fields might return many results if published:
for book in books: query += ' published=? AND'
if book['id'] == id: to_filter.append(published)
results.append(book) if author:
query += ' author=? AND'
# Use the jsonify function from Flask to convert our list of to_filter.append(author)
# Python dictionaries to the JSON format. if not (id or published or author):
return page_not_found(404)
query = query[:-4] + ';'
conn = sqlite3.connect('books.db')
conn.row_factory = dict_factory
cur = conn.cursor()
results = cur.execute(query, to_filter).fetchall()
return jsonify(results) return jsonify(results)
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment