Flask is a popular Python web framework that is often used to build RESTful APIs. In this tutorial, we will go over the steps to build a simple RESTful API with Flask.
Prerequisites
Before we get started, you'll need to have the following installed on your machine:
- Python 3.x
- Flask
- Flask-RESTful
You can install Flask and Flask-RESTful using pip, the Python package manager. Open a terminal and run the following commands:
pip install Flask pip install Flask-RESTful
Building a Simple RESTful API with Flask
Let's start by creating a Flask application and setting up a route to handle GET requests. In a new Python file, import Flask and Flask-RESTful:
pythonfrom flask import Flask
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
We have created a new Flask app and initialized an instance of the Flask-RESTful API. Now, let's define a resource for handling GET requests:
pythonclass HelloWorld(Resource):
def get(self):
return {'message': 'Hello, World!'}
This defines a new resource called HelloWorld
that inherits from Flask-RESTful's Resource
class. We have defined a get()
method that returns a simple JSON message.
Now, let's add a route to our Flask app that maps to this resource:
pythonapi.add_resource(HelloWorld, '/')
This will map the HelloWorld
resource to the root route of our Flask app.
Finally, we need to run our Flask app:
pythonif __name__ == '__main__':
app.run(debug=True)
Now, if you run this Python file and navigate to http://localhost:5000/
in your browser, you should see the message "Hello, World!".
Handling POST Requests
In order to handle POST requests, we need to define a new resource that handles the post()
method:
pythonclass User(Resource):
def post(self):
return {'message': 'User created'}
This defines a new resource called User
that has a post()
method that returns a simple JSON message.
Now, let's add a route to our Flask app that maps to this resource:
pythonapi.add_resource(User, '/user')
This will map the User
resource to the /user
route of our Flask app.
To test our new POST request, we can use a tool like curl
or Postman
. Send a POST request to http://localhost:5000/user
, and you should see the message "User created" in the response.
Conclusion
In this tutorial, we have shown how to build a simple RESTful API with Flask. We defined two resources, HelloWorld
and User
, that handled GET and POST requests respectively. Flask-RESTful makes it easy to create RESTful APIs with Flask, and we hope this tutorial has given you a good starting point for building your own Flask-based APIs.