The Wayback Machine - https://web.archive.org/web/20241013185047/https://www.geeksforgeeks.org/python-build-a-rest-api-using-flask/
Open In App

Python | Build a REST API using Flask

Last Updated : 25 Feb, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: Introduction to Rest API

REST stands for REpresentational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data.

In this article, we will build a REST API in Python using the Flask framework. Flask is a popular micro framework for building web applications. Since it is a micro-framework, it is very easy to use and lacks most of the advanced functionality which is found in a full-fledged framework. Therefore, building a REST API in Flask is very simple.

There are two ways of creating a REST API in Flask:

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

Libraries required:

flask_restful can be installed via the pip command:

 sudo pip3 install flask-restful 

Method 1: using only Flask

Here, there are two functions: One function to just return or print the data sent through GET or POST and another function to calculate the square of a number sent through GET request and print it.




# Using flask to make an api
# import necessary libraries and functions
from flask import Flask, jsonify, request
  
# creating a Flask app
app = Flask(__name__)
  
# on the terminal type: curl http://127.0.0.1:5000/
# returns hello world when we use GET.
# returns the data that we send when we use POST.
@app.route('/', methods = ['GET', 'POST'])
def home():
    if(request.method == 'GET'):
  
        data = "hello world"
        return jsonify({'data': data})
  
  
# A simple function to calculate the square of a number
# the number to be squared is sent in the URL when we use GET
# on the terminal type: curl http://127.0.0.1:5000 / home / 10
# this returns 100 (square of 10)
@app.route('/home/<int:num>', methods = ['GET'])
def disp(num):
  
    return jsonify({'data': num**2})
  
  
# driver function
if __name__ == '__main__':
  
    app.run(debug = True)


Output:

Executing the square function:

Method 2: Using flask-restful

Flask Restful is an extension for Flask that adds support for building REST APIs in Python using Flask as the back-end. It encourages best practices and is very easy to set up. Flask restful is very easy to pick up if you’re already familiar with flask.

In flask_restful, the main building block is a resource. Each resource can have several methods associated with it such as GET, POST, PUT, DELETE, etc. for example, there could be a resource that calculates the square of a number whenever a get request is sent to it. Each resource is a class that inherits from the Resource class of flask_restful. Once the resource is created and defined, we can add our custom resource to the api and specify a URL path for that corresponding resource.




# using flask_restful
from flask import Flask, jsonify, request
from flask_restful import Resource, Api
  
# creating the flask app
app = Flask(__name__)
# creating an API object
api = Api(app)
  
# making a class for a particular resource
# the get, post methods correspond to get and post requests
# they are automatically mapped by flask_restful.
# other methods include put, delete, etc.
class Hello(Resource):
  
    # corresponds to the GET request.
    # this function is called whenever there
    # is a GET request for this resource
    def get(self):
  
        return jsonify({'message': 'hello world'})
  
    # Corresponds to POST request
    def post(self):
          
        data = request.get_json()     # status code
        return jsonify({'data': data}), 201
  
  
# another resource to calculate the square of a number
class Square(Resource):
  
    def get(self, num):
  
        return jsonify({'square': num**2})
  
  
# adding the defined resources along with their corresponding urls
api.add_resource(Hello, '/')
api.add_resource(Square, '/square/<int:num>')
  
  
# driver function
if __name__ == '__main__':
  
    app.run(debug = True)


Output:



Previous Article
Next Article

Similar Reads

Implement a Python REST API with Flask & Flasgger
Building a RESTful API in Python can be straightforward with Flask, a lightweight and flexible web framework. To add comprehensive documentation and interactive features to the API, Flasgger is a powerful tool that integrates Swagger UI with Flask. This article guides you through the process of implementing a REST API using Flask and Flasgger. What
4 min read
Documenting Flask Endpoint using Flask-Autodoc
Documentation of endpoints is an essential task in web development and being able to apply it in different frameworks is always a utility. This article discusses how endpoints in Flask can be decorated to generate good documentation of them using the Flask-Autodoc module. This module provides the following features - Helps to document endpoints of
4 min read
Minify HTML in Flask using Flask-Minify
Flask offers HTML rendering as output, it is usually desired that the output HTML should be concise and it serves the purpose as well. In this article, we would display minification of output routes of Flask responses using the library - Flask-Minify. Advantages of MinificationWebsites load faster as fewer lines are there to upload and download.Ban
12 min read
How to use Flask-Session in Python Flask ?
Flask Session - Flask-Session is an extension for Flask that supports Server-side Session to your application.The Session is the time between the client logs in to the server and logs out of the server.The data that is required to be saved in the Session is stored in a temporary directory on the server.The data in the Session is stored on the top o
4 min read
How to Integrate Flask-Admin and Flask-Login
In order to merge the admin and login pages, we can utilize a short form or any other login method that only requires the username and password. This is known as integrating the admin page and Flask login since it simply redirects users to the admin page when they log in. Let's is how to implement this in this article. Integrate Flask Admin and Fla
8 min read
Flask URL Helper Function - Flask url_for()
In this article, we are going to learn about the flask url_for() function of the flask URL helper in Python. Flask is a straightforward, speedy, scalable library, used for building, compact web applications. It is a micro framework, that presents developers, useful tools, and, features, for coding REST APIs, and backend data processing, of web apps
11 min read
How to Build a Web App using Flask and SQLite in Python
Python-based Flask is a microweb framework. Typically, a micro-framework has little to no dependencies on outside frameworks. Despite being a micro framework, practically everything may be developed when and as needed utilizing Python libraries and other dependencies. In this post, we'll develop a Flask application that collects user input in a for
4 min read
Build a Text Translator Web App using Flask and Azure Cognitive Services
We're going to create a website that will translate text into multiple languages using Artificial Intelligence(AI). We'll use Flask framework for the Front end and Azure Cognitive Services(collection of AI services) for the Back end. To get started writing our Flask application with Python, we need to set up our development environment, which will
7 min read
Build Blog website using Flask
In this article, we'll explore how to build a dynamic blog website using Flask, a lightweight and versatile Python web framework. Flask provides developers with the tools needed to create robust web applications, and its simplicity makes it an excellent choice for beginners and experienced developers alike. Requirements Basics of HTML & CSSBoot
15+ min read
Create GitHub API to fetch user profile image and number of repositories using Python and Flask
GitHub is where developers shape the future of software, together, contribute to the open-source community, manage Git repositories, etc. It is one of the most used tools by a developer and its profile is shared to showcase or let others contribute to its projects. Web Scraping using python is also one of the best methods to get data. In this artic
5 min read
How to Build a Simple Android App with Flask Backend?
Flask is an API of Python that allows us to build up web applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. A Web-Application Framework or Web Framework is the collection of modules and libraries
8 min read
Build a Flask application to validate CAPTCHA
In this article, we are going a build a web application that can have a CAPTCHA. CAPTCHA is a tool you can use to differentiate between real users and automated users. CAPTCHAs are usually found on the login pages or on payment pages. What is CAPTCHA? Captcha is strategy used to ensure sites against spam. Objective is to prevent intuitive sites fro
5 min read
Build Your Own Microservices in Flask
Nowadays Python is everywhere. This is majorly due to its simplicity and wide range of applications. Flask is a lightweight web framework for building web applications in Python. Creating microservices with Flask is straightforward. In this article, we will start with a basic "hello world" microservice. Following that, we'll delve into the creation
5 min read
Setup API for GeeksforGeeks user data using WebScraping and Flask
Prerequisite: WebScraping in Python, Introduction to Flask In this post, we will discuss how to get information about a GeeksforGeeks user using web scraping and serve the information as an API using Python's micro-framework, Flask. Step #1: Visit the auth profile To scrape a website, the first step is to visit the website. Step #2: Inspect the Pag
3 min read
Sending Emails Using API in Flask-Mail
Python, being a powerful language don’t need any external library to import and offers a native library to send emails- “SMTP lib”. “smtplib” creates a Simple Mail Transfer Protocol client session object which is used to send emails to any valid email id on the internet. This article revolves around how we can send bulk customised emails to a group
3 min read
Create Cricket Score API using Web Scraping in Flask
Cricket is one of the famous outdoor sport played worldwide. There are very few APIs providing live scoreboards and none of them are free to use. Using any of the scoreboards available we can create API for ourselves. This method not only works for Cricket Scoreboard but also for any information available online. Following is the flow in which this
6 min read
How to Get Data from API in Python Flask
In modern web development, APIs (Application Programming Interfaces) play a crucial role in enabling the interaction between different software systems. Flask, a lightweight WSGI web application framework in Python, provides a simple and flexible way to create APIs. In this article, we'll explore how to get data from an API using Python Flask. We'l
2 min read
Form Submission API with Swagger Editor and Python Flask
Creating user-friendly APIs is essential for seamless interaction between applications. Leveraging tools like Swagger Editor alongside Python Flask, developers can streamline the process of designing, documenting, and implementing APIs. In this guide, we'll explore how to craft a Form Submission API using Swagger Editor integrated with Python Flask
3 min read
How to Create a basic API using Django Rest Framework ?
Django REST Framework is a wrapper over the default Django Framework, basically used to create APIs of various kinds. There are three stages before creating an API through the REST framework, Converting a Model's data to JSON/XML format (Serialization), Rendering this data to the view, and Creating a URL for mapping to the views.This article revolv
4 min read
Top 10 Python REST API Frameworks in 2024
In a rapidly changing web development scene, REST APIs have emerged as the underlying functionality that allows for the development of scalable and efficient applications. Python is a simple and versatile language, much helped by a mature ecosystem of frameworks for building REST APIs. The right choice of framework for a project is a decision that
10 min read
How to write a simple Flask API for hello world?
Prerequisites: Introduction to REST API REST stands for Representational State Transfer and is an architectural style used in modern web development. It defines a set of rules/constraints for a web application to send and receive data. In this article, we are going to learn how to create a simple REST API that returns 'Hello World', with the help o
3 min read
How to return a JSON response from a Flask API ?
Flask is one of the most widely used python micro-frameworks to design a REST API. In this article, we are going to learn how to create a simple REST API that returns a simple JSON object, with the help of a flask. Prerequisites: Introduction to REST API What is a REST API? REST stands for Representational State Transfer and is an architectural sty
3 min read
How to connect ReactJS with flask API ?
Reactjs is one of the best frontend libraries for building frontend single-page applications. It is been developed and maintained by Facebook with a large community. Flask is a backend micro-framework written in Python for the rapid development process. It is famous for its simplicity and independence. It does not need any external library for work
3 min read
Flask API Authentication with JSON Web Tokens
Authentication is the process of verifying the identity of the user. It checks whether the user is real or not. It is used to provide access to resources only to valid users. There are two types of Authentication: Single Factor Authentication: In this only one piece of information is needed to verify the identity of the user and to check that the u
7 min read
How to Create a Flask API with MariaDB on AWS EC2
In this article, We are going to create an ec2 instance, install a MySQL database using MariaDB on the ec2 instance, and create an API of Login using the flask python framework. Flask is a micro web framework written in Python. MariaDB is one of the most popular open-source relational database management systems and could be used as a great replace
6 min read
How To Configure Flask API To Your Domain Name On AWS EC2?
In this article, We are going to create a Flask API on an EC2 Instant and we will learn how to configure it with a domain name using Gunicorn and nginx(NGINX). Flask is a web microframework, it’s a Python module that lets you develop web applications easily. A domain name is a string of text that maps to an alphanumeric IP address, used to access a
8 min read
How to throttle API with Django Rest Framework
Have you ever passed through an overbridge and noticed the sign stating the bridge weight restriction? Those restrictions are put in place to ensure public safety. Django REST Framework uses a similar process named throttling that controls the rate of requests that the client can make to an API. This rate limit restriction can ensure scalability, p
4 min read
Django REST API - CRUD with DRF
Django REST Framework is used to create web APIs very easily and efficiently. This is a wrapper around the Django Framework. There are three stages before creating an API through the REST framework, Converting a Model’s data to JSON/XML format (Serialization), Rendering this data to the view, and Creating a URL for mapping to the views. Django REST
7 min read
Creating First REST API with FastAPI
FastAPI is a cutting-edge Python web framework that simplifies the process of building robust REST APIs. In this beginner-friendly guide, we'll walk you through the steps to create your very first REST API using FastAPI. By the end, you'll have a solid foundation for building and deploying APIs with ease. What is FastAPI? FastAPI is a modern, fast
5 min read
Adding Permission in API - Django REST Framework
There are many different scenarios to consider when it comes to access control. Allowing unauthorized access to risky operations or restricted areas results in a massive vulnerability. This highlights the importance of adding permissions in APIs.   Django REST framework allows us to leverage permissions to define what can be accessed and what actio
7 min read
Article Tags :
Practice Tags :