Create a WEB API
Here's a simple example of a web API built using Python and the Flask framework. This API provides basic CRUD (Create, Read, Update, Delete) operations for managing a list of items.
### Prerequisites:
- Python installed on your machine
- Flask library installed (`pip install Flask`)
### Step 1: Create a new Python file (e.g., `app.py`) and paste the following code:
```python
from flask import Flask, jsonify, request
app = Flask(__name__)
# Sample data - a list of items
items = [
{'id': 1, 'name': 'Item 1', 'description': 'This is item 1'},
{'id': 2, 'name': 'Item 2', 'description': 'This is item 2'}
]
# Read - GET all items
@app.route('/api/items', methods=['GET'])
def get_items():
return jsonify(items)
# Read - GET an item by ID
@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
# Create - POST a new item
@app.route('/api/items', methods=['POST'])
def add_item():
new_item = {
'id': items[-1]['id'] + 1 if items else 1,
'name': request.json['name'],
'description': request.json.get('description', '')
}
items.append(new_item)
return jsonify(new_item), 201
# Update - PUT an existing item
@app.route('/api/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
item = next((item for item in 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)
return jsonify({'message': 'Item not found'}), 404
# Delete - DELETE an item by ID
@app.route('/api/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
global items
items = [item for item in items if item['id'] != item_id]
return jsonify({'message': 'Item deleted'})
if __name__ == '__main__':
app.run(debug=True)
```
### Step 2: Run the API
To run the API, navigate to the directory containing your `app.py` file in the terminal or command prompt and run:
```bash
python app.py
```
This will start the Flask development server, and the API will be accessible at `http://127.0.0.1:5000/`.
### Step 3: Test the API
You can use tools like [Postman](https://www.postman.com/) or `curl` commands in the terminal to test the API. Below are some example commands:
- **Get all items:**
```bash
curl http://127.0.0.1:5000/api/items
```
- **Get an item by ID:**
```bash
curl http://127.0.0.1:5000/api/items/1
```
- **Create a new item:**
```bash
curl -X POST -H "Content-Type: application/json" -d '{"name": "NewItem", "description": "This is a new item"}' http://127.0.0.1:5000/api/items
```
- **Update an item:**
```bash
curl -X PUT -H "Content-Type: application/json" -d '{"name": "UpdatedItem", "description": "This is an updated item"}' http://127.0.0.1:5000/api/items/1
```
- **Delete an item:**
```bash
curl -X DELETE http://127.0.0.1:5000/api/items/1
```
This is a basic example, but it demonstrates the fundamental principles of building a RESTful web API with Flask. You can expand on this by adding authentication, connecting to a database, or implementing more complex logic.
Comments
Post a Comment