Skip to content

Instantly share code, notes, and snippets.

@sausax
Created April 3, 2023 21:41
Show Gist options
  • Save sausax/36bc0346dd0961948e46a53fcb57f1d3 to your computer and use it in GitHub Desktop.
Save sausax/36bc0346dd0961948e46a53fcb57f1d3 to your computer and use it in GitHub Desktop.
Write a flask post api to save name, age an occupation in a postgres database. Also write a get api to retrieve the list of user saved in db
Here's an example of a Flask post API to save a user's name, age, and occupation in a PostgreSQL database:
First, create a new Flask application and install the Flask-SQLAlchemy library, which allows you to easily work with a PostgreSQL database:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:password@localhost/dbname'
db = SQLAlchemy(app)
Next, define the User model that corresponds to the user data you want to save in the database:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
age = db.Column(db.Integer)
occupation = db.Column(db.String(50))
In the route that handles the POST request, use the db.session.add() method to add the new user to the database and then call db.session.commit() to save the changes:
@app.route('/user', methods=['POST'])
def create_user():
name = request.json['name']
age = request.json['age']
occupation = request.json['occupation']
user = User(name=name, age=age, occupation=occupation)
db.session.add(user)
db.session.commit()
return {'message': 'User created successfully'}
Here's an example of a Flask GET API to retrieve the list of users saved in the database:
@app.route('/user', methods=['GET'])
def get_users():
users = User.query.all()
return jsonify([u.serialize() for u in users])
The above code is an example, you may need to modify it based on your specific requirements.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment