Build a Bookstore web App API With Python Flask
Beginners guide for building Successful Restful api’s with flask
Today we live in an interconnected world surrounded by data making it possible to get all the information we need with a simple click and one of the most important ways through which enables which are able to make efficient and effective use of this data is with the use of an API.We will be building a book store web app api using python flask in this article. Already there’s a lot of information out there which could provide you with answers to commonly asked questions such as ;
- what is an Api
- what is flask
- why use flask for Api development
With all that being said,lets begin by;
SETTING UP A VIRTUAL ENVIRONMENT
Just like with any other python project, we begin by creating a working directory and then setting up a virtual environment by using the command
conda create -n myvirtualenv
ACTIVATING OUR VIRTUAL ENVIRONMENT
To activate our virtual environment, we type in activate the command
activate myvirtualenv
INSTALLING PACKAGES
The packages needed for this are ;
Flask
Httpie
We install this using the command pip install packagename inside of our virtual environment
Next:
Inside of our working directory, we create two blank python files
app.py: Which functions as the main entry point for our app
book_store.py : This holds our mock data containing basic information about our bookstore such as id,book_title,book_author,publisher,publication_date
In our book_store.py file we create a list containing mock data for our bookstore as seen below;
books = [
{"id": 1,"book_title": "God of War","book_author": "jack Hughman","publisher": "chowa","description": 'spoils of war'},{"id": 2,"book_title": "Splinter cell","book_author": "Tom clancy","publisher": "cross","description": 'splinting of cells'},{"id": 3,"book_title": "Monsters","book_author": "jackie bu","publisher": "meme","description": "Are monsters real"},]
we then move to our app.py were we perform the following as seen below;
- Import all the necessary packages
- create an instance of the Flask class
- and lastly we start the flask server
from flask import Flask, jsonify, requestfrom http import HTTPStatus # includes different http statusesfrom book_store import booksapp = Flask(__name__)#creates Flask class instanceif __name__ == '__main__': #starts the flask server
app.run()
The app.py file will then contain the following four functions;
- ) get_books: This function displays all our mock data in the book_store.py file by converting the list of books to JSON format then responding to the client as seen below.We do this by using the Flask route decorator so the route will route the get_books function .To specify this route only gets the GET request, we use the methods=[‘GET’] argument.
@app.route('/books', methods=['GET'])
def get_books():
return jsonify({'data': books})
2.) get_book:This function enbales us to get a single book by using its id.we do this by passing “‘/books/<int:book_id>’, methods=[‘GET’]” into the route decorator. These implies the integer value in the route will be assigned to the id of the particular variable in our mock data.
@app.route('/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
book = next(
(book for book in books if book['id'] ==book_id),None)
if book:
return jsonify(book)
return jsonify(
{"message": "Book not found"}),HTTPStatus.NOT_FOUND
3.) update_book: This function enables us update the books in our mock data using the argument methods=[‘PUT’] in our route decorator. If the book is not found in the JSON format we return ‘book not found’ with an HTTP STUTUS OF 404 if the book is found we perform the book.update function and put in all the update information.Finally we convert the updated data to JSON format and return an HTTP STUTUS OF 201
@app.route('/books/<int:book_id>', methods=['PUT'])
def update_book(book_id):
book = next((book for book in books if book['id'] == book_id), None) #finds out book with id equals book_id
if not book:
return jsonify(
{'message': "book not found"}),HTTPStatus.NOT_FOUND data = request.get_json()
book.update(
{
'title': data.get('book_title'), 'author': data.get('book_author'), 'publisher': data.get('publisher'), 'description': data.get('description'),
}
)
return jsonify(book)
1.) create_book:This function enables us to create a new book data which we can add to our mock data using the “methods=[‘POST’]” argument in the route decorator. We use the request.get_json()method to get all the necessary information we require from the client POST request. The information we get will be stored in a book dictionary object with a self incremented id and then append to our books list in the book_data.py file.The result will be returned in a JSON format together with and HTTP 201 status
@app.route('/books', methods=['POST'])
def create_book():
data = request.get_json()
title = data.get('book_title')
author = data.get('book_author')
publisher = data.get('publisher')
description = data.get('description')
book = {
"id": len(books)+1, # remember we start counting from zero
"title": title,
"author": author,
"publisher": publisher,
"description": description
}
books.append(book)
return jsonify(books), HTTPStatus.CREATED
RUNNING OUR DEVELOPMENT SERVER
In order to run our development server, we use the command flask run
CONCLUSION
These concludes our Bookstore Api development life cycle but inorder to test our API endpoints, we can use curl or postman.
The complete code for this can be found on my github repo alongside the necessary credits.