In this tutorial, we will learn how to create an UPDATE API to a database using Python and Flask. We will build an API that allows us to update records in a database using a Python script.
To get started, make sure you have Python installed on your system. You can download Python from the official website (https://www.python.org/downloads/). Additionally, you will need to install Flask, a web framework for Python, which can be installed via pip using the following command:
pip install Flask
Next, we will create a new Python file called app.py
and add the following code snippet to set up our Flask application and create routes for our API:
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
age = db.Column(db.Integer, nullable=False)
@app.route('/update', methods=['POST'])
def update_user():
data = request.json
user = User.query.get(data['id'])
if user:
user.name = data.get('name', user.name)
user.age = data.get('age', user.age)
db.session.commit()
return jsonify({'message': 'User updated successfully'})
return jsonify({'message': 'User not found'})
if __name__ == '__main__':
app.run(debug=True)
In the code above, we have defined a User
model with id
, name
, and age
columns. We have also created an update_user
route that accepts a JSON payload with the id
, name
, and age
fields to update the corresponding record in the database.
To test our API, let’s create a sample JSON payload to update a user’s record. Create a new Python script called update_user.py
with the following code:
import requests
url = 'http://localhost:5000/update'
data = {'id': 1, 'name': 'John Doe', 'age': 30}
response = requests.post(url, json=data)
print(response.json())
Make sure to replace the url
with your Flask application’s URL. Now, run the update_user.py
script to send a POST request to the /update
route and update the user record with the specified id
, name
, and age
values.
That’s it! You have successfully created an UPDATE API to a database using Python and Flask. You can expand this API by adding authentication, error handling, and input validation to make it more robust and secure.
I hope you found this tutorial helpful. Feel free to ask if you have any questions. Happy coding!
Main bajaj emi card se no cost EMI