EXP3
EXP3
Aim:
To create a simple REST API using python to do the GET, POST, PUT and DELETE operations
Algorithm:
Step 1: Start
Step 2: Install Flask
Step 3: Start the Flask App
Step 4: Use Postman to Test Endpoints
Step 5: View Server Output
Step 6: Stop
Procedure:
Step1: Installation of python and click on the “use admin privileges when installing py.exe ”,”Add
python.exe to PATH”.
Step2: Select customize installation and click next.
Step3: In advanced options click on “install python 3.13 for all users” and click install
Step4: In setup progress installation in process.
Step8:open python (or) IDLE enter the code and save the code. (ex. “api.py”)
Program:
from flask import Flask, jsonify, request
app = Flask(__name__)
# Sample data
data = [
{'id': 1, 'name': 'Item 1'},
{'id': 2, 'name': 'Item 2'},
{'id': 3, 'name': 'Item 3'}
]
# GET request to retrieve all items
@app.route('/items', methods=['GET'])
def get_items():
return jsonify({'items': data})
# GET request to retrieve a specific item by ID
@app.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
item = next((item for item in data if item['id'] == item_id), None)
if item:
return jsonify({'item': item})
else:
return jsonify({'message': 'Item not found'}), 404
# POST request to add a new item
@app.route('/items', methods=['POST'])
def add_item():
new_item = {'id': len(data) + 1, 'name': request.json['name']}
data.append(new_item)
return jsonify({'item': new_item}), 201
# PUT request to update a specific item by ID
@app.route('/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
item = next((item for item in data if item['id'] == item_id), None)
if item:
item['name'] = request.json['name']
return jsonify({'item': item})
else:
return jsonify({'message': 'Item not found'}), 404
# DELETE request to remove a specific item by ID
@app.route('/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
global data
data = [item for item in data if item['id'] != item_id]
return jsonify({'message': 'Item deleted'}), 200
if __name__ == '__main__':
app.run(debug=True)
Step9: After run the code, the output will be display in command prompt.
Step11: open the postman and click on the “Run as administrator”.Then click “continue with google” enter
the email ID.
Step12: After login this site is trying to open postman ,click on the check box and click
open.
Result:
Thus, the experiment to create a simple REST API using python to do the GET, POST, PUT and
DELETE operations is executed and verified successfully.