Practical 3
Create a Simple REST Service
Software Tools Required:
Code Editor: Visual Studio Code (VS Code)
API Testing Software Application: Postman
Framework: Flask (micro web framework)
Downloads Required:
Python: Download Python | [Link]
Postman: Download Postman | Get Started for Free
(Create Account/ Log in with Google)
After Downloading Python, Set the Path in Environment Variable in User Variables > Path >
Edit > New and Paste the Path for Python.
New version is 3.13, Here the version is 3.12 so following the same for new version.
Till Python312: Copy Directory Path
Start > Python 3.13.1 (64 bit) > Open File Location > Python 3.13.1 (64 bit)
Till Python312\Scripts: Copy the Directory Path
Start > Python 3.13.1 (64 bit) > Open File Location > Python 3.13.1 (64 bit) > Open File
Location > Scripts
Demonstration:
Check Version:
Python Programming Language
Step 1: Install Flask: Make sure you have Python installed on your system.
Open cmd and type the following command
pip install Flask
Demonstration:
Step 2: Create a folder name SimpleRESTService, Open with VS Code and create python
file.
Check and Install Extensions for Python
Extensions:
Python
Python Debugger
Filename: [Link]
Code:
from flask import Flask, jsonify, request
app = Flask(__name__)
# Sample data
data = [
{'id': 1, 'name': 'Item 1'},
{'id': 2, 'name': 'Item 2'},
]
# Endpoint to get all items
@[Link]('/items', methods=['GET'])
def get_items():
return jsonify({'items': data})
# Endpoint to get a specific item by ID
@[Link]('/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
# Endpoint to add a new item
@[Link]('/items', methods=['POST'])
def add_item():
new_item = {'id': len(data) + 1, 'name': [Link]['name']}
[Link](new_item)
return jsonify({'message': 'Item added successfully', 'item': new_item}), 201
# Run the application
if __name__ == '__main__':
[Link](debug=True)
Output:
View>Terminal
Type
Path> python [Link]
Demonstration:
Postman
API Testing Software Application to Test the API
Open Postman
# Endpoint to get all items
Send a GET Request:
URL: [Link]
Response:
{
"items": [
"id": 1,
"name": "Item 1"
},
"id": 2,
"name": "Item 2"
Demonstration:
# Endpoint to get a specific item by ID
Send a GET Request:
URL: [Link]
Response:
{
"item": {
"id": 1,
"name": "Item 1"
}
}
Provides specific id from Sample Data available i.e., URL: [Link]
Demonstration:
Throws Error when not item not found from Sample Data. Example
URL: [Link]
Demonstration:
# Endpoint to add a new item
Send a POST Request:
URL: [Link]
Body: Set the body to raw JSON and include:
{"name":"item3"}
Response:
"item": {
"id": 3,
"name": "item3"
},
"message": "Item added successfully"
Demonstration:
---------------------------------