Welcome to our comprehensive guide on creating API resources using Flask! By the end of this tutorial, you'll have a solid understanding of how to create, test, and deploy APIs for web applications. Let's dive in!
API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate with each other. In this tutorial, we'll be focusing on building APIs using Flask, a Python web framework.
Before we get started, make sure you have the following prerequisites:
First, let's install Flask. If you haven't installed it yet, open your terminal and run:
pip install flaskNext, create a new directory for your project and navigate to it:
mkdir flask-api-resources
cd flask-api-resourcesNow, let's create a simple Flask application with a single API endpoint. Create a new file called app.py and add the following code:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def hello():
return jsonify({'message': 'Welcome to our API!'})
if __name__ == '__main__':
app.run(debug=True)This code creates a new Flask app, defines a route at the root ('/') of the application, and returns a JSON response with a welcoming message. To test the application, run it with:
python app.pyNow, open your browser and navigate to http://127.0.0.1:5000/. You should see the JSON response we created. ✅
To create API resources, we'll be working with SQLAlchemy, a popular ORM (Object-Relational Mapping) library for Python. Install it using:
pip install flask-sqlalchemyNow, update app.py to include SQLAlchemy and create a simple database model:
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
age = db.Column(db.Integer)
def __repr__(self):
return f"<User {self.name}>"
db.create_all()Here, we define a User model with id, name, and age columns. We also create the database table for the User model using the db.create_all() function.
Now, let's create API endpoints for creating, retrieving, updating, and deleting users:
@app.route('/users', methods=['POST'])
def add_user():
user = User(name=request.json['name'], age=request.json['age'])
db.session.add(user)
db.session.commit()
return jsonify({'message': 'User added'})
@app.route('/users', methods=['GET'])
def get_users():
users = User.query.all()
output = []
for user in users:
output.append({
'id': user.id,
'name': user.name,
'age': user.age
})
return jsonify(output)
# ...
if __name__ == '__main__':
app.run(debug=True)In this example, we create two API endpoints:
/users (POST): Add a new user to the database/users (GET): Retrieve all users from the databaseYou can create similar endpoints for updating and deleting users.
What is the primary key for the User model?
Congratulations! You've now created your first API resources using Flask. In this tutorial, we covered:
Remember to keep practicing and exploring Flask to build powerful and efficient APIs for your projects. Happy coding! 🎉