Here is an example of a simple REST API built using Flask in Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | pythonCopy codefrom flask import Flask, jsonify, request app = Flask(__name__) # A simple in-memory database to store some data database = [ {"id": 1, "name": "Alice", "age": 25}, {"id": 2, "name": "Bob", "age": 30}, {"id": 3, "name": "Charlie", "age": 35} ] # API endpoint to get all the records @app.route('/records', methods=['GET']) def get_all_records(): return jsonify(database) # API endpoint to get a specific record by ID @app.route('/records/<int:id>', methods=['GET']) def get_record_by_id(id): for record in database: if record['id'] == id: return jsonify(record) return jsonify({"error": "Record not found"}), 404 # API endpoint to create a new record @app.route('/records', methods=['POST']) def create_record(): data = request.json # Generate a new ID for the record new_id = max([record['id'] for record in database]) + 1 # Add the new record to the database database.append({"id": new_id, "name": data['name'], "age": data['age']}) return jsonify({"message": "Record created successfully"}) # API endpoint to update an existing record @app.route('/records/<int:id>', methods=['PUT']) def update_record(id): data = request.json for record in database: if record['id'] == id: # Update the record with the new data record['name'] = data['name'] record['age'] = data['age'] return jsonify({"message": "Record updated successfully"}) return jsonify({"error": "Record not found"}), 404 # API endpoint to delete an existing record @app.route('/records/<int:id>', methods=['DELETE']) def delete_record(id): for i, record in enumerate(database): if record['id'] == id: # Remove the record from the database database.pop(i) return jsonify({"message": "Record deleted successfully"}) return jsonify({"error": "Record not found"}), 404 if __name__ == '__main__': app.run(debug=T |
In this example, we have defined five API endpoints:
/records
: GET method to retrieve all records or POST method to create a new record/records/<id>
: GET method to retrieve a record by ID, PUT method to update an existing record, or DELETE method to delete a record
The jsonify
function is used to convert the data to JSON format and return it to the client. The request
object is used to retrieve data from the client’s request. The debug=True
argument when running the application enables debug mode, which provides detailed error messages in case something goes wrong.