Building my first Flask API
Module 1 :

Hi all,
This write-up is aimed to share the knowledge i gained. I recently tried building a Flask API with python, tried playing around few HTTP methods available, created database and added Authentication to the API created.
In this blog I tried to explain them in simple words, so that somewhere a newbie looking for a resource (just like i did recently) might get benefited someday..
I divided the task into six smaller modules for better understanding and easy approach. In this blog we are going to learn through Coding it. I assume the reader has a basic Programming skill, basic Python knowledge and few Terminal Commands.
Dont worry, if you are new to python/flask, I added adequate comments for the snippets we code here. So, just start coding parallely, you will get it in due course, as we proceed.
So, lets start Learning by Doing…!!!
After finishing the complete series of this blog, you would be able to build and integrate the following things on your own :
- Getting Data
- Posting Data
- Updating Data
- Deleting Data
- Storing Data In SQL DB
- Adding Authentication To Our API
1.GETTING DATA
1.1 Building our First Flask Application
1.2 Returning List of Books from our API
1.3 Returning a single Book from our API
2.POSTING DATA
2.1 Adding a POST route
2.2 Getting the Request body sent by the client
2.3 Sending POST request to our Flask API using POSTMAN app
2.4 Sanitizing Data sent in POST request
2.5 Testing how well we sanitized
2.6 Adding New book to our Store
2.7 Mistake to be aware
2.8 Setting Status codes and Response
2.9 Setting location Headers
2.10 Handling invalid POST requests
3.UPDATING DATA
3.1 Adding a PUT route
3.2 Getting the Client’s request
3.3 Sending PUT request to Flask
3.4 Finishing up the PUT route
3.5 Adding a PATCH route
3.6 Defining our PATCH route
3.7 Finishing up our PATCH route
4.DELETING DATA
4.1 Adding a DELETE route
4.2 Coding our DELETE route
4.3 Sending DELETE requests to our Flask App
4.4 Finishing up our DELETE route
5.STORING DATA IN SQL DB
5.1 Configuring a Flask SQLAlchemy Database
5.2 Defining Tables and Columns in Flask SQLAlchemy
5.3 Creating the Database
5.4 Defining a Data model with Flask SQLAlchemy
5.5 Updating our Data Model to Query our Database
5.6 Updating our Data Model to Delete Entries from our Database
5.7 Updating our Data Model to Update Table Entries
5.8 Updating our Data Model to Replace Table Entries
5.9 Returning back JSON from our Data Model
5.10 Updating our Flask App to use Our Book Model
5.11 Verifying the Book Model integration
6.ADDING AUTHENTICATION TO OUR API
6.1 Creating a JWT Tokens
6.2 Adding Authentication for our GET route
6.3 Creating a Database for Users who are allowed API access
6.4 Creating Users ,who are allowed API access
6.5 Having User Login to get a Token
6.6 Creating Decorators to Add API Authentication
6.7 Adding Authentication for all our routes using Decorators
In our first read lets focus on the first module – GETTING DATA. We simplify the concepts by taking an example ‘Book List’. By the end of this first module, you would be able to do the following on your own:
- Building your First Flask Application
- Returning a List of Books from your API
- Returning a single Book from your API
Lets get started…!!! 🙂
MODULE : 1 – GETTING DATA
1.1 Building our First Flask Application
Prerequisite:
- python3 (preferably, Check installed version by giving python –version in CLI)
- Flask (pip install will do the magic for you)
- Postman (link: https://www.getpostman.com/downloads/ )
- SublimeText (in case you need it, link: https://www.sublimetext.com/3)
Create a python file and open it in an editor of your choice. I used Sublime Text Editor.
The Terminal commands to create and open the file in editor (in my case, SublimeText) are :
$ touch RSapp.py
$ subl RSapp.py
we have now opened a python file ( RSapp.py ) to build our first flask application.
First thing first, import Flask class into our python file
from flask import Flask #importing the Flask Class
Create an instance of this Flask class. 1st argument is the name of the Application’s module or Package. It is needed, so that Flask knows where to look for templates, static files and packages, when needed.
For eg., if the python interpreter is running that module, the source file, as the main program,then it sets the __name__ variable equal to value of main i.e., __name__=”main”, if it is imported from another module, the name will be set to the module’s name i.e., __name__=”modulesName”
app = Flask(__name__)
print(__name__) #prints the name when we start the server,this is just for our ref.,
Route Decorator:
Creating our 1st route with a route decorator. Route decorator binds a function to a URL. In simple words when someone hits the path specified by this route function, then the method defined below the route decorator will be called.
@app.route(‘/’) #route decorator
def hello_world(): #function that returns hello world
return ‘Hello world .!’ #when route directory is hit, it returns hello world
app.run(port=5000) #running that flask instance at localhost port 5000
Runnable Code Snippet_1.1 – Building our First Flask Application:
#RSapp.py
from flask import Flask
app = Flask(__name__)
print(__name__)
@app.route('/')
def hello_world():
return 'Hello world .!'
app.run(port=5000)
Now, save and run the app from Terminal (Note: cd to your app’s file location)
CLI Output:
rs@rs-pc:~/RSflaskAPI$ python RSapp.py #command to run our app
__main__ //output of print(__name__) statement
* Serving Flask app “RSapp”
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
On hitting the URL , we get Hello world .! message displayed in a default browser window localhost.
Note: By hitting CTRL+C from the terminal we can stop our app Server , ^C indicates the server has been stopped successfully
1.2 Returning List of Books from our API – (first API endpoint, which allows a Client on the API to get all the Books in our Store)
Import jsonify library along with Flask class, so that we can return a JSON object.
#importing Flask Class and jsonify library
from flask import Flask,jsonify
#creating an instance of Flask class
app = Flask(__name__)
#Creating books List[], with 2 Dictionaries{}
books=[ #List
{ #1st Dictionary
‘name’ : ‘Book1’, #fields- name , price & isbn
‘price’ : 20,
‘isbn’ : 123
},
{ #2nd Dictionary
‘name’ : ‘Book2’,
‘price’ : 10,
‘isbn’ : 456
}
]
#route decorator
whenever someone goes to route,in this case we make it as /books
@app.route(‘/books’) #by default GET request
def get_books(): #method get_books() will be called and
#to return a pythonList
return {‘books’: books} #returns the LIST ,but we want a JSON object
so we return the jsonified books list,this is the reason we imported jsonify library.
return jsonify({‘books’:books})
Note: if someone goes to route. By default, it is set to GET request
i.e., GET /books
Note: if we want to override that, we can add a different method as follows.,
@app.route(‘/books’, methods=[‘POST’]), we will this discuss later in our upcoming module.
Runnable Snippet_1.2: Returning List of Books from our API :
#RSapp.py
from flask import Flask,jsonify
app = Flask(__name__)
books=[
{
'name' : 'Book1',
'price' : 20,
'isbn' : 123
},
{
'name' : 'Book2',
'price' : 10,
'isbn' : 456
}
]
@app.route('/books')
def get_books():
return jsonify({'books':books})
app.run(port=5000)
Now, save and run the app from Terminal
CLI Output:
rs@rs-pc:~/RSflaskAPI$ python RSapp.py #command to run our app
* Serving Flask app “RSapp”
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
On hitting the URL http://127.0.0.1:5000/books , we get the json data of the books List displayed in our route directory /books localhost.
1.3 Returning a single Book from our API – (allows a Client on the API to get all the Data of a Single Book in our Store, through ISBN)
Here we import request library along with Flask and jsonify.
#import request library, along with others as earlier
from flask import Flask,jsonify,request
Create an instance of Flask class, create books List[], with 2 Dictionaries{} and create route decorators , as we did in our previous program.
app = Flask(__name__)
books=[
{
‘name’ : ‘Book1’,
‘price’ : 20,
‘isbn’ : 123
},
{
‘name’: ‘Book2’,
‘price’: 10,
‘isbn’: 456
}
]
#GET /store
@app.route(‘/books’)
def get_books():
return jsonify({‘books’:books})
To get all the Data of a Single Book in our Store, through ISBN:
@app.route(‘/books/<int:isbn>’) #GET request by passing isbn_no Note: typecasted to int
def get_books_by_isbn(isbn): #ISBN that’s passed in URL will be passed into ftn as arg(stored in variable isbn)
return_value={} #defined return_value as empty dictionary object
for book in books: #in our List
if book[“isbn”] == isbn: #if matches the isbn passed(var in the rightside)
return_value = { #then adds the properties defined in List into the return_value
‘name’: book[“name”],
‘price’: book[“price”]
}
return jsonify(return_value) #return_value is a Dictionary,but we need a JSON object
app.run(port=5000)
Runnable Snippet_1.3: Returning a single Book from our API – (allows a Client on the API to get all the Data of a Single Book in our Store, through ISBN):
#RSapp.py-Returning a single Book from our API
from flask import Flask,jsonify
app = Flask(__name__)
books=[
{
'name' : 'Book1',
'price' : 20,
'isbn' : 123
},
{
'name' : 'Book2',
'price' : 10,
'isbn' : 456
}
]
#GET /books
@app.route('/books')
def get_books():
return jsonify({'books':books})
#GET /books/ISBN_NUMBER - ”GET request by passing isbn_no”
#GET /books/123
@app.route('/books/<int:isbn>')
def get_books_by_isbn(isbn):
return_value={}
for book in books:
if book["isbn"] == isbn:
return_value = {
'name': book["name"],
'price': book["price"]
}
return jsonify(return_value)
app.run(port=5000)
Now, save and run the app from Terminal
CLI Output:
rs@rs-pc:~/RSflaskAPI$ python RSapp.py #command to run our app
* Serving Flask app “RSapp”
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
On hitting the URL http://127.0.0.1:5000/books , we get the json data of the books List displayed in our route directory /books localhost.
From the List take an isbn (from our example isbn:456 is of Book2) and give it in URL http://127.0.0.1:5000/books/456
we get the json data of the book (Book2 from our example)
We have successfully completed the first module (Getting Data), please do read and try your hands and let me know, if there is any error.
We will play with some HTTP methods available in the upcoming modules. Visit them, as well and Stay updated.
Corrections and Suggestions are highly appreciated. Please leave a reply, in case you find any..
*CLI – Command Line Interface
For Complete Sourcecode visit my Github repo: Link provided in the final module.
RS-codes

2 thoughts on “First time with Flask-Python -Module1”