- 15th Jan 2024
- 18:41 pm
Students reach out to our Python Helpers asking for help with Flask and Django. As data analysis using Python is gaining popularity in universities, students get assignments on building Web Development and APIs using Python Libraries. One such popular question in Python programming that students often ask us and its solution has been provided below. If you need any more details then please reach out to our Python Helpers and they will provide you with a customised solution to your Python problem.
Python Question
Build a RESTful API using frameworks like Flask to handle data requests and interactions with an external application.
Python Assignment Solution
The below Python Code creates a basic API with endpoints to handle data requests and interactions.
- The
/items
endpoint supports GET (retrieve all items) and POST (create a new item) operations. - The
/items/
endpoint supports GET (retrieve a specific item), PUT (update a specific item), and DELETE (delete a specific item) operations.
You can run this script, and the API will be accessible at http://127.0.0.1:5000/
. Make sure to replace the sample data with your actual data source and customize the endpoints based on your application's requirements.
from flask import Flask, jsonify, request
app = Flask(__name__)
# Sample data (replace this with your actual data source)
data = {
"items": [
{"id": 1, "name": "Item 1", "description": "Description 1"},
{"id": 2, "name": "Item 2", "description": "Description 2"},
{"id": 3, "name": "Item 3", "description": "Description 3"}
]
}
# Endpoint to get all items
@app.route('/items', methods=['GET'])
def get_items():
return jsonify({"items": data["items"]})
# Endpoint to get a specific item by ID
@app.route('/items/', methods=['GET'])
def get_item(item_id):
item = next((item for item in data["items"] if item["id"] == item_id), None)
if item:
return jsonify({"item": item})
else:
return jsonify({"message": "Item not found"}), 404
# Endpoint to add a new item
@app.route('/items', methods=['POST'])
def add_item():
new_item = {
"id": len(data["items"]) + 1,
"name": request.json.get('name'),
"description": request.json.get('description')
}
data["items"].append(new_item)
return jsonify({"item": new_item}), 201
# Endpoint to update an existing item
@app.route('/items/', methods=['PUT'])
def update_item(item_id):
item = next((item for item in data["items"] if item["id"] == item_id), None)
if item:
item['name'] = request.json.get('name', item['name'])
item['description'] = request.json.get('description', item['description'])
return jsonify({"item": item})
else:
return jsonify({"message": "Item not found"}), 404
# Endpoint to delete an item
@app.route('/items/', methods=['DELETE'])
def delete_item(item_id):
global data
data["items"] = [item for item in data["items"] if item["id"] != item_id]
return jsonify({"message": "Item deleted"})
if __name__ == '__main__':
app.run(debug=True)
About The Author
Introducing Sarah Thompson, a seasoned Python developer with a Master's in Computer Science. Sarah's expertise shines in "Building RESTful APIs with Flask," where years of experience in web development converge. Join her on a journey of creating scalable APIs, as Sarah imparts invaluable insights and practical wisdom in this intricate realm.