Designing a RESTful API Introduction to Flask References
Building a RESTful API: Flask
Design of Telematic Systems
Miguel A Hombrados Herrera
Universidad Carlos III de Madrid
23/10/2023
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 1 / 29
Designing a RESTful API Introduction to Flask References
1 Designing a RESTful API
2 Introduction to Flask
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 2 / 29
Designing a RESTful API Introduction to Flask References
Roadmap
The main steps for designing the API (before coding) are:
1 Identify the resources you want to share in your server.
2 Define the endpoints associated with the resources.
3 Determine the data format of your data (Will be JSON for us)
4 Define the methods required
5 Define the necessary success and error responses for the
operations (200,201,404, etc...)
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 3 / 29
Designing a RESTful API Introduction to Flask References
Roadmap
1.-Identify the resources you want to share in your server
• Find a word that uniquely identifies the resource
• By convention, the names should be plural, lowercase and
not include verbs
• For example, students, courses, books, locations or
operations
• Consider the possible nested relations between the resources.
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 4 / 29
Designing a RESTful API Introduction to Flask References
Roadmap
2.-Define the endpoints
Endpoint Description
/courses Access to all courses’ information
/students Access to all students’ profiles
/courses/<course_id> Access to course’s #<course_id> information
/students/<student_id> Access to student’s #<student_id> information
2b.-Define nested endpoints
/courses/<course_id>/students/<student_id>
This is used to access student #<student_id> belonging to course
#<course_id>
NOTE: You will define CRUD ( GET, PUT, POST, ...) operations
to handle the endpoints defined
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 5 / 29
Designing a RESTful API Introduction to Flask References
Roadmap
3.-Determine the data format of your data
• Pick the data format to serialise the data.
• The most popular formats nowadays are JSON an XML.
• In the context of this course, we will stick to JSON.
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 6 / 29
Designing a RESTful API Introduction to Flask References
Roadmap
4.-Define the methods required
• Define all the Python request methods required to handle the
endpoint/resources defined with CRUD operations (PUT,
POST, GET, DELETE)
• Define the auxiliary functions required by your request
methods.
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 7 / 29
Designing a RESTful API Introduction to Flask References
Roadmap
5.-Define the necessary success and error responses
• Define how your API will respond to client requests.
• The response must follow a uniform format.
• The response must include a status code (200,201,400, etc..)
according to the events.
• Consider potential sources of error: Updating or deleting
missing resources, retrieving non existing resources, using the
wrong format, etc...
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 8 / 29
Designing a RESTful API Introduction to Flask References
Python alternatives
Python offers several alternatives to building APIs with Python:
• Flask
• FastAPI
• Django REST framework
• Tornado
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 9 / 29
Designing a RESTful API Introduction to Flask References
1 Designing a RESTful API
2 Introduction to Flask
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 10 / 29
Designing a RESTful API Introduction to Flask References
What is Flask?
• Flask is a web framework for Python.
• It simplifies URL routing. Creating endpoints and assigning
them specific actions based on HTTP (GET, PUT,
DELETE,...)
• It is not inherently RESTful.
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 11 / 29
Designing a RESTful API Introduction to Flask References
Running a Flask server: Hello World!
[Link]
1 from flask import Flask
2 app = Flask ( __name__ )
3
4 @app . route ( ’/ ’)
5 def hello () :
6 return ’ Hello World ! ’
Terminal
1 $ export FLASK_APP = app . py
2 $ flask run
Run the command wherever you have the file. This will launch a
server in [Link]:5000 with [Link] running in it.
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 12 / 29
Designing a RESTful API Introduction to Flask References
Running a Flask server: Hello World!
• If you open your browser and type the local host in port 5000,
you will see the server is up and running.
• Nothing would stop you from running this in an address
different from localhost.
Don’t forget to shut down the server (Ctrl + C)!
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 13 / 29
Designing a RESTful API Introduction to Flask References
Decorators
• This @[Link](’/’) is called decorator.
• Decorators are a unique feature of Python.
• Start with "@", and they modify whatever method below it.
• In this case, "app" makes reference to the object just created.
• The input argument in the method route is relative path or
partial URL that determines where the action will be applied.
• Here ’/’ defines the home page or root of the site.
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 14 / 29
Designing a RESTful API Introduction to Flask References
Running a Flask server: Hello World!
[Link]
1 from flask import Flask
2 app = Flask ( __name__ )
3
4 @app . route ( ’/ resources ’)
5 def hello () :
6 return ’ Hello World ! ’
Terminal
1 $ export FLASK_APP = app . py
2 $ flask run
Run the command wherever you have the file. This will launch a
server in [Link]:5000 with [Link] running.
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 15 / 29
Designing a RESTful API Introduction to Flask References
Running a Flask server: Hello World!
• Now "Hello World!" is displayed in the path /resources/.
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 16 / 29
Designing a RESTful API Introduction to Flask References
Implementing GET in Flask
flask_server_v0.py
1 # flask_server_v0 . py
2 from flask import Flask , jsonify
3 app = Flask ( __name__ )
4 college_students = [
5 { ’ id ’:1 , ’ name ’: ’ Ganga ’ , ’ age ’: 20 , ’ major
’: ’ Informática ’ , ’ grade ’: ’A + ’} ,
6 { ’ id ’:2 , ’ name ’: ’ Luis ’ , ’ age ’: 22 , ’ major ’
: ’ Ingeniería ’ , ’ grade ’: ’A + ’} ,
7 { ’ id ’:3 , ’ name ’: ’ VJ ’ , ’ age ’: 21 , ’ major ’:
’ Biología ’ , ’ grade ’: ’A + ’}
8 ]
9 @app . get ( " / students " )
10 def get_students () :
11 return jsonify ( college_students )
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 17 / 29
Designing a RESTful API Introduction to Flask References
Implementing GET in Flask
Client request to flask_server_v0
1 import requests
2
3 url = ’ http :// localhost :5000/ students ’
4 response = requests . get ( url )
5 print ( response . json () )
Client output
1 c o l le g e _ s t u d e n t s = [
2 { ’ id ’:1 , ’ name ’: ’ Ganga ’ , ’ age ’: 20 , ’ major ’: ’
Informática ’ , ’ grade ’: ’A + ’} ,
3 { ’ id ’:2 , ’ name ’: ’ Luis ’ , ’ age ’: 22 , ’ major ’: ’
Ingeniería ’ , ’ grade ’: ’A + ’} ,
4 { ’ id ’:3 , ’ name ’: ’ VJ ’ , ’ age ’: 21 , ’ major ’: ’ Biología ’ ,
’ grade ’: ’A + ’}
5 ]
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 18 / 29
Designing a RESTful API Introduction to Flask References
Implementing GET in Flask
If you type in the browser [Link] (setting the
port to 5000)
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 19 / 29
Designing a RESTful API Introduction to Flask References
Implementing POST in Flask
API flask_server_post_v0
1 # f l a s k _ s e r v e r _ p o s t _ v 0 . py
2 from flask import Flask , jsonify , request
3 import requests
4 app = Flask ( __name__ )
5 # DATA DATA DATA DATA DATA
6 def _find_next_id () :
7 return max ( student [ " id " ] for student in
c o l l e g e _ s t u den t s ) + 1
8 @app . post ( " / students " )
9 def add_student () :
10 if request . is_json :
11 student = request . get_json ()
12 student [ " id " ] = _find_next_id ()
13 c o l l e g e _ s t u den t s . append ( student )
14 return student , 201
15 return { " error " : " Request must be JSON " } , 415
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 20 / 29
Designing a RESTful API Introduction to Flask References
Implementing POST in Flask
API flask_server_post_v0
1 @app . post ( " / students " )
2 def add_student () :
3 if request . is_json : # CHECK ’S IF THE
DATA IS JSON FORMAT
4 student = request . get_json () # GET ’S
THE DATA OF THE HTTP REQUEST IN
JSON
5 student [ " id " ] = _find_next_id ()
6 college_students . append ( student )
7 return student , 201
8 return { " error " : " Request must be JSON "
} , 415
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 21 / 29
Designing a RESTful API Introduction to Flask References
Implementing POST in Flask
API flask_server_post_v0 It simply finds out what is the maxi-
mum id number stored and "college_students" and adds +1.
1 def _find_next_id () :
2 return max ( student [ " id " ] for student in
college_students ) + 1
An alternative form of doing this would be:
1 def _find_next_id () :
2 return max ( students , key = lambda x : x [ ’
id ’] ) + 1
• Notice the first underscore on the function’s name.
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 22 / 29
Designing a RESTful API Introduction to Flask References
Client request POST to Flask API
Client POST request to API
1 import requests
2 url = ’ http :// localhost :5000/ students ’
3 new_student = { ’ name ’: ’ Jenny ’ ,
4 ’ age ’: 20 ,
5 ’ major ’: ’ Social Sciences ’ ,
6 ’ grade ’: ’A ’}
7 response = requests . post ( url , json =
new_student )
8 print ( response . json () )
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 23 / 29
Designing a RESTful API Introduction to Flask References
Client request POST to Flask API
Client output
1 { ’ age ’: 20 , ’ grade ’: ’A ’ , ’ id ’: 4 , ’ major ’:
’ Social Sciences ’ , ’ name ’: ’ Jenny ’}
If you type in your browser [Link]:5000/students/ you will find
out how the students "database" was updated with the new student
"Jenny".
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 24 / 29
Designing a RESTful API Introduction to Flask References
Implementing DELETE in Flask
API flask_server_delete_v0
1 @app . delete ( ’/ students / < int : students_id > ’)
2 def delete_stude nt_id ( students_id ) :
3 student = _ f i n d _ d i c t s _ b y _ k e y _ v a l u e (
college_students , ’ id ’ , students_id )
4 if student is None :
5 abort (404)
6 else :
7 _delete_element_from_dictionary (
college_students , students_id )
8 return {} , 204
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 25 / 29
Designing a RESTful API Introduction to Flask References
Client request DELETE to Flask API
Client output
1 >>> response . status_code
2 204
trying to get [Link]() will raise an error, since the
dictionary was empty.
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 26 / 29
Designing a RESTful API Introduction to Flask References
Implementing PUT in Flask
API flask_server_put_v0.py
1 @app . put ( ’/ students / < int : students_id > ’)
2 def update_student ( students_id ) :
3 if request . is_json :
4 student = _ f i n d _ d i c t s _ b y _ k e y _ v a l u e (
college_students , ’ id ’ , students_id
)
5 partial_student = request . get_json ()
6 student_updated = _replace_values (
student , partial_student )
7 return student_updated , 200
8 return { " error " : " Request must be JSON "
} , 415
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 27 / 29
Designing a RESTful API Introduction to Flask References
Client request PUT to Flask API
Client POST request to API
1 url = ’ http :// localhost :5000/ students /2 ’
2 new_data = { ’ id ’ :2 , ’ grade ’: ’A - ’}
3 response = requests . put ( url , json = new_data )
Client output
1 >>> print ( response . json () )
2 { ’ age ’: 22 , ’ grade ’: ’A - ’ , ’ id ’: 2 , ’ major ’:
’ Ingeniería ’ , ’ name ’: ’ Luis ’}
3 >>> response . status_code
4 200
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 28 / 29
Designing a RESTful API Introduction to Flask References
References
[1] Real Python. API Integration in Python. https:
//[Link]/api-integration-in-python/.
Accessed on November 17, 2023.
[2] [Link]. [Link].
[Link] Accessed on November 17,
2023.
[3] MO Faruque Sarker and Sam Washington. Learning Python
Network Programming. Packt Publishing Ltd, 2015.
[4] Author Unknown. Flask - Python Advanced Web Applications.
Accessed on November 20, 2023.
Miguel A Hombrados Herrera Universidad Carlos III de Madrid
Building a RESTful API: Flask 29 / 29