Develop Database Driven REST API with Python in 10 Minutes

Original article was published by Dario Radečić on Artificial Intelligence on Medium


API development

Right now, we’ll handle five different things:

And all of that logic is written in a single class, called UserManager. Feel free to name yours as you wish, but this one seems appropriate. Flask-RESTful is very friendly when it comes to the amount of boilerplate code we need to write. It’s minimal. To start, we need to declare a class that inherits from Flask-RESTful.Resource. Here’s a starter code:

class UserManager(Resource): 
pass

We’ll start by implementing the logic for fetching one/all users. Every following code block be inside the UserManager class.

Get user(s)

Inside the UserManager class, we’ll declare a static method called get. The naming is essential this time, as the method’s name stands for the type of HTTP request we intend to make. A request is the most appropriate one for fetching data, so that’s what we’ll use.

Here’s the logic:

  • Check to see if a user appended the ID parameter to the URL – if yes, we want data for a single user. If not, we want data for all users
  • Make a query through SQLAlchemy accordingly
  • Return the data in JSON format using the flask.jsonify function

And here’s the code:

@staticmethod
def get():
try: id = request.args['id']
except Exception as _: id = None

if not id:
users = User.query.all()
return jsonify(users_schema.dump(users))
user = User.query.get(id)
return jsonify(user_schema.dump(user))

Let’s proceed with the insertion of new users.

Insert user

This time we’ll use the HTTP request. That means the user should pass the data for a new user in the JSON format — more on that in the testing section. Also, our new static method must be named post.

Here’s the logic we have to implement:

  • Fetch provided JSON data for username, password, first name, last name, and age
  • Create an instance of the User class with the provided data
  • Add this user to the database and commit the transaction
  • Return a message indicating the user was inserted

It’s a relatively simple function. Here’s the code:

@staticmethod
def post():
username = request.json['username']
password = request.json['password']
first_name = request.json['first_name']
last_name = request.json['last_name']
age = request.json['age']

user = User(username, password, first_name, last_name, age)
db.session.add(user)
db.session.commit()

return jsonify({
'Message': f'User {first_name} {last_name} inserted.'
})

Let’s proceed with the update of existing users.

Update user

To update an existing user, we’ll use the HTTP request. The static method is then named, you’ve guessed it, put. Here’s the overview of the logic:

  • Check if a user ID was passed in the call. If not, an error message is returned. That’s because we are updating only a single user at a time
  • Fetch provided JSON data for username, password, first name, last name, and age
  • Set the values to the database user according to the provided data and commit the transaction
  • Return a message indicating the user was updated

This method is a bit more complicated than the previous one, but is still reasonably easy to implement:

@staticmethod
def put():
try: id = request.args['id']
except Exception as _: id = None

if not id:
return jsonify({ 'Message': 'Must provide the user ID' })

user = User.query.get(id)
username = request.json['username']
password = request.json['password']
first_name = request.json['first_name']
last_name = request.json['last_name']
age = request.json['age']

user.username = username
user.password = password
user.first_name = first_name
user.last_name = last_name
user.age = age

db.session.commit()
return jsonify({
'Message': f'User {first_name} {last_name} altered.'
})

Delete user

This is the final methods we’ll implement. Its task is to remove an individual user from the database. I’m sure you can guess by now what type of HTTP request we’ll make and how the method must be called. Here’s the logic:

  • Check if a user ID was passed in the call. If not, an error message is returned. That’s because we are deleting only a single user at a time
  • Delete a user from the database and commit the transaction
  • Return a message indicating the user was updated

Here’s the code:

@staticmethod
def delete():
try: id = request.args['id']
except Exception as _: id = None

if not id:
returnjsonify({ 'Message': 'Must provide the user ID' })

user = User.query.get(id)
db.session.delete(user)
db.session.commit()

return jsonify({
'Message': f'User {str(id)} deleted.'
})

And that’s it for the entire UserManager class. Let’s finish the file next and begin with the testing.

Finishing touches

To finish with the app.py file, we need to attach the UserManager class to some actual endpoint. I’ve decided to name mine /api/users, but the naming decision is up to you.

Also, we need to run the Flask app once the file is executed from the Terminal. Here’s the code for both:

api.add_resource(UserManager, '/api/users')

if __name__ == '__main__':
app.run(debug=True)

And that’s it — we can begin with the testing.