Table of Contents
Building REST APIs is a common task in web development, allowing different applications to communicate over the internet. Python, combined with the Flask framework, provides a simple and efficient way to create these APIs. Flask’s lightweight nature makes it ideal for small to medium-sized projects.
Setting Up Flask
To start building a REST API with Flask, first install the Flask package using pip:
pip install Flask
Next, create a new Python file and import Flask. Initialize the app and define routes to handle API requests.
Creating API Endpoints
Endpoints are URLs that respond to specific HTTP methods such as GET, POST, PUT, and DELETE. Flask uses decorators to define these routes.
For example, a simple endpoint to retrieve data might look like:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route(‘/api/data’, methods=[‘GET’])
def get_data():
data = {‘message’: ‘Hello, World!’}
return jsonify(data)
Running the API
To run the Flask application, include the following code at the end of your script:
if __name__ == ‘__main__’:
app.run(debug=True)
Testing the API
Once the server is running, you can test the API by navigating to http://127.0.0.1:5000/api/data in a web browser or using tools like Postman or curl.
- Start the Flask server
- Open a browser or API client
- Send a GET request to the endpoint
- Receive the JSON response