/  Technology   /  How to Create a Web API using Flask and Python

How to Create a Web API using Flask and Python

Flask is a web framework written in python. It provides tools, libraries, and technologies that allow you to build a web application.


Installing Flask

Python is the prerequisite for installing flask and we need to install virtualenv, which is a virtual python environment builder. It helps the user to create multiple python environments. You can use the following command to install virtualenv.

pip install virtualenv


Once we install virtualenv we will create a folder and then we will set up our virtualenv in that folder. It can be done by using the following commands.

mkdir myproject
cd myproject
virtualenv venv


To activate the corresponding environment, you can use

venv\scripts\activate


Now we are ready to install flask, so now you can use:

pip install flask


After this you will have flask ready in your system.


What is API?

API stands for Application Programming Interface. It is a part of a computer program designed to be used by another program. A web API allows information to be manipulated by other programs via the internet. For example, Twitter’s web API, you can write a program in a language like a python, JavaScript that can perform a task such as favoriting tweets or collecting tweet metadata.

When you are using or building APIs, you will encounter these terms frequently:


HTTP:

It stands for Hypertext Transfer Protocol. HTTP is used to transfer data over the web. It allows users of the world wide web to exchange information found on web pages.


URL:

URL stands for uniform resource locator and is used to specify the address on the World Wide Web. It starts with ‘http://’ or ‘https://’ it is often followed by ‘www’ and then the name of the website you want to visit.


JSON:

It stands for JavaScript Object Notation. It is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate.


REST:

REST stands for Representational State Transfer. It is an architectural style and an approach to communication that is often used in the development of web services. REST web services are a way of providing compatibility between computer systems on the internet.

In this article,  we will create a REST API in python using a flask framework.

There are two ways of creating a REST API in the flask:

  1. Using flask without any external libraries
  2. Using flask_restful library

flask_restful can be installed by using the command

pip install flask-restful


  1. Using Flask only

In this, we will use two functions. First will just return the data sent through GET or POST and the second function will calculate the area of a circle from the number sent through GET request taking it as a radius.

from flask import Flask, jsonify, request
app = Flask(_name_)

@app.route('/greet', methods=['GET', 'POST'])

def hello():
    if(request.method=='GET'):
    data = 'Happy Coding'
    return jsonify ({'message' : data})

@app.route('/area/<int:num>', methods=['GET'])
def rad(num):
      return jsonify({'area' : 3.14*num**2})

 if _name_='_main_':
app.run(debug=True)


To get the output you need to type the following in terminal for the first function:

curl http://127.0.0.1:5000/greet


Output:

{

                     “message” : “Happy Coding”

                   }


For the second function

curl http://127.0.0.1:5000/area/5


Output:

{

                    “area” : 78.5

                  }


2. Using flask_restful

from flask import Flask, jsonify, request
from flask_restful import Resource, API

app=Flask(_name_)
api=Api(app)

class greet(Resource):
def get(self):
      return jsonify({'message' : Happy Coding })

def post(self):
      data = request.get_json()
      return jsonify({'data': data})

class area(Resource):
def get(self,num):
      return jsonify({'area' : 3.14*num**2})

api.add_resource(greet, '/')
api.add_resource(area, '/area/<int:num>')

if _name_=='_main_'
app.run(debug=True)


To run this program you can use the same step as we used in the first one.

Leave a comment