How to Create a RESTful API with Flask in Python

Published on Aug. 22, 2023, 12:15 p.m.

To create a RESTful API with Flask in Python, follow these steps:

  1. Install Flask and Flask-RESTful libraries: First, install the Flask and Flask-RESTful libraries using pip. You can do this by running the following command:
pip install flask flask-restful
  1. Create a Flask application object: Create a Flask application object by importing the Flask class from the flask module and initializing it.
from flask import Flask

app = Flask(__name__)
  1. Define the endpoint and methods for the REST API: Define the endpoint and methods for the REST API, such as GET, POST, PUT or DELETE, using the Flask-RESTful module.
from flask_restful import Resource, Api

api = Api(app)

class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}

api.add_resource(HelloWorld, '/hello')
  1. Start the Flask application: Use the run method to start the Flask application on a web server.
if __name__ == '__main__':
    app.run(debug=True)
  1. Test the API endpoint: Once the server is running, test the API endpoint ‘/hello’ by accessing it in a web browser or using a REST client like Postman.
GET http://localhost:5000/hello

This will return a JSON response with the message “hello: world”. You can modify the resource classes and methods to handle different HTTP requests and provide different endpoints for your API.

POST endpoint

here is an example of creating a POST endpoint using Flask-RESTful:

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class Example(Resource):
    def post(self):
        json_data = request.get_json()
        # do something with the json data
        return {'status': 'success'}

api.add_resource(Example, '/example')

if __name__ == '__main__':
    app.run(debug=True)

In this example, we create a class called “Example” that inherits from the Flask-RESTful “Resource” class. We define a single method, “post”, which will be called when a POST request is made to the ‘/example’ endpoint. Inside the “post” method, we use Flask’s built-in ‘request’ object to retrieve the JSON data from the client’s request. Then we can process this data and return a response as JSON data.

We then use the Flask-RESTful “api” object to add the “Example” resource class to the API, and start the Flask app.

You can test this API by sending a POST request to the ‘/example’ endpoint with some JSON data in the request body. For example, you can use the following cURL command:

curl -X POST http://localhost:5000/example -H 'Content-Type: application/json' -d '{"name": "John"}'

This should return a JSON response with the status message “success”.