create a business directory rest api in python

Here's a simple example of creating a business directory REST API in Python using Flask and SQLAlchemy:

main.py
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///businesses.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class Business(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    address = db.Column(db.String(100), nullable=False)

    def __repr__(self):
        return f'Business(name={self.name}, address={self.address})'

@app.route('/businesses', methods=['GET'])
def get_businesses():
    businesses = Business.query.all()
    return jsonify([business.__dict__ for business in businesses]), 200

@app.route('/businesses/<int:business_id>', methods=['GET'])
def get_business(business_id):
    business = Business.query.get_or_404(business_id)
    return jsonify(business.__dict__), 200

@app.route('/businesses', methods=['POST'])
def create_business():
    business_data = request.json
    business = Business(name=business_data['name'], address=business_data['address'])
    db.session.add(business)
    db.session.commit()
    return jsonify(business.__dict__), 201

@app.route('/businesses/<int:business_id>', methods=['PUT'])
def update_business(business_id):
    business = Business.query.get_or_404(business_id)
    business_data = request.json
    business.name = business_data['name'] if 'name' in business_data else business.name
    business.address = business_data['address'] if 'address' in business_data else business.address
    db.session.commit()
    return jsonify(business.__dict__), 200

@app.route('/businesses/<int:business_id>', methods=['DELETE'])
def delete_business(business_id):
    business = Business.query.get_or_404(business_id)
    db.session.delete(business)
    db.session.commit()
    return '', 204

if __name__ == '__main__':
    app.run(debug=True)
1890 chars
53 lines

In this code, we define a Business class as a SQLAlchemy model, with id, name, and address attributes. We then define five Flask routes for interacting with the API: get_businesses for getting a list of all businesses, get_business for getting a single business by ID, create_business for creating a new business, update_business for updating an existing business by ID, and delete_business for deleting a business by ID.

To run this API, simply save the code to a file (e.g., app.py) and run it using the command python app.py. The API will listen on port 5000 by default, and you can interact with it using any REST client, such as Postman or cURL.

gistlibby LogSnag