Step 1: Setup
First, make sure you have Python installed on your system. You can download Python from the official website:(https://www.python.org/downloads/)
Next, install Flask using pip, the Python package manager. Open a terminal or command prompt and run the following command:
pip install Flask
Step 2: Create the Flask App
Create a new Python file (e.g., app.py) and import the necessary modules:
from flask import Flask, jsonify, request
Next, initialize the Flask app:
app = Flask(__name__)
Step 3: Define Routes and Endpoints
In Flask, you define routes using the @app.route decorator. Each route corresponds to a specific URL, and each URL will be associated with a function that handles the request and returns the response.
Let's create a simple API with two endpoints: one to get a list of items and another to get details of a specific item.
# Sample data - you can replace this with your own data or use a database
items = [
{"id": 1, "name": "Item 1"},
{"id": 2, "name": "Item 2"},
{"id": 3, "name": "Item 3"}
]
# Endpoint to get all items
@app.route('/api/items', methods=['GET'])
def get_items():
return jsonify(items)
# Endpoint to get details of a specific item
@app.route('/api/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
item = next((item for item in items if item['id'] == item_id), None)
if item:
return jsonify(item)
return jsonify({"message": "Item not found"}), 404
Step 4: Run the Flask App
At the end of your app.py file, add the following lines to run the app:
if __name__ == '__main__':
app.run(debug=True)
Step 5: Test the API
Save the file and run it using the following command in the terminal:
python app.py
Your Flask app should now be running locally at http://127.0.0.1:5000/.
To test the API, you can use tools like curl, Postman, or simply use your web browser.
To get all items, open your web browser and go to http://127.0.0.1:5000/api/items.
To get details of a specific item (e.g., item with ID 2), go to http://127.0.0.1:5000/api/items/2.
Congratulations! You have just created a simple RESTful API with Python and Flask. From here, you can continue exploring more advanced features of Flask, like handling POST, PUT, and DELETE requests, using a database, authentication, etc. Happy coding!.
Top comments (0)