Flask is a framework that is widely used to create APIs in Python. Flask is a simple yet powerful web framework that is designed to help us get started quickly and easily, with the ability to scale up to complex applications.
Flask is often referred to as micro because it was built with a simple but extensible core.
In this shot, we are going to learn how to create a simple REST API that returns a simple JSON object, with the help of Flask.
An API is a contract between an information provider and an information user that establishes the content required by the consumer and the content required by the producer.
REST stands for Representational State Transfer. A RESTFUL API allows for interaction with RESTFUL web services by conforming to the constraints of REST architectural style.
Let’s create a minimal app to test it.
Run these commands in the terminal to install Flask:
pip install pipenv
pipenv shell
pipenv install Flask
The following code will be part of the file app.py
:
from flask import Flask,jsonify,request
app = Flask(__name__)
@app.route('/')
def Home():
info = {
"school" : 'Federal University Of Technology Owerri',
"department" : "Biochemistry",
'level': "500L"
}
return jsonify(info) # returning a JSON response
if __name__=='__main__':
app.run(debug=True)
In the code above, we return the info
variable, which is in JSON format.
The jsonify()
function in Flask serializes data to JavaScript Object Notation (JSON) format.