make a py api
- User
make a py api
- Assistant
make a py api
Creating a simple Python API can be done using popular frameworks such as Flask or FastAPI. In this example, I will use Flask to demonstrate how to build a basic RESTful API:
First, make sure you have Flask installed. You can install it using pip:
pip install Flask
Next, create a new file, e.g., app.py, and write the following code:
from flask import Flask, jsonify, request
app = Flask(__name__)
# Sample data for demonstration
data = [
{'id': 1, 'name': 'John Doe'},
{'id': 2, 'name': 'Jane Smith'}
]
@app.route('/api/users', methods=['GET'])
def get_users():
return jsonify(data)
@app.route('/api/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
user = next((user for user in data if user['id'] == user_id), None)
if user:
return jsonify(user)
return jsonify({'error': 'User not found'}), 404
@app.route('/api/users', methods=['POST'])
def create_user():
new_user = request.get_json()
new_user['id'] = len(data) + 1
data.append(new_user)
return jsonify(new_user), 201
@app.route('/api/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
user = next((user for user in data if user['id'] == user_id), None)
if user:
updated_data = request.get_json()
user.update(updated_data)
return jsonify(user)
return jsonify({'error': 'User not found'}), 404
@app.route('/api/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
global data
user = next((user for user in data if user['id'] == user_id), None)
if user:
data = [user for user in data if user['id'] != user_id]
return jsonify({'message': 'User deleted successfully'})
return jsonify({'error': 'User not found'}), 404
if __name__ == '__main__':
app.run(debug=True)
Open a terminal in the directory where you created app.py, and run the API using:
python app.py
You should see output indicating that the Flask server is running, typically on http://127.0.0.1:5000/.
You can test the API using tools such as Postman, cURL, or your browser.
Here are some example requests:
GET all users:
GET http://127.0.0.1:5000/api/users
GET a user by ID:
GET http://127.0.0.1:5000/api/users/1
Create a new user:
POST http://127.0.0.1:5000/api/users
Content-Type: application/json
Body:
{
"name": "New User"
}
Update an existing user:
PUT http://127.0.0.1:5000/api/users/1
Content-Type: application/json
Body:
{
"name": "Updated User"
}
Delete a user:
DELETE http://127.0.0.1:5000/api/users/1
You have successfully created a simple RESTful API using Flask! From here, you can expand the API with features like authentication, database integration, error handling, and more, depending on your requirements.
Not yet included in a published release.