In this tutorial, we'll explain how to create your first REST API with Flask on Ubuntu server.
REST APIs (Representational State Transfer Application Programming Interfaces) are essential for building scalable web applications. Flask, a micro web framework for Python, is an excellent choice for creating REST APIs due to its simplicity and flexibility. In this tutorial, we'll walk through the steps of setting up a basic REST API using Flask on Ubuntu.
Prerequisites
Before we begin, ensure you have the following:
- An Ubuntu dedicated server or KVM VPS (20.04 or later).
- Python 3.8 or later installed.
- Basic knowledge of Python and Flask.
REST API with Flask on Ubuntu
Step 1: Install Python and Pip
First, update your system's package list and install Python and pip, the Python package manager.
sudo apt update
sudo apt install python3 python3-pip -y
Verify the installation by checking the Python and pip versions:
python3 --version
pip3 --version
Step 2: Set Up a Virtual Environment
It's best practice to use a virtual environment for your Flask projects to manage dependencies separately. Create and activate a virtual environment as follows:
sudo apt install python3-venv -y
python3 -m venv flask-api
source flask-api/bin/activate
Your terminal prompt will change to indicate that the virtual environment is active.
Step 3: Install Flask
With the virtual environment activated, install Flask using pip:
pip install Flask
Step 4: Create a Basic Flask Application
Let's start by creating a basic Flask application. In your project directory, create a file named app.py:
nano app.py
Add the following code:
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to the Flask REST API!"
if __name__ == '__main__':
app.run(debug=True)
This simple application has one route (/) that returns a welcome message.
Step 5: Create a REST API Endpoint
Let's extend the application by adding a REST API endpoint. We'll create a simple API to manage a list of users.
Replace the content of app.py
with the following code:
from flask import Flask, jsonify, request
app = Flask(__name__)
# In-memory database (a list of users)
users = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"},
{"id": 3, "name": "Charlie"}
]
# Get all users
@app.route('/users', methods=['GET'])
def get_users():
return jsonify(users)
# Get a single user by ID
@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
user = next((u for u in users if u['id'] == user_id), None)
if user:
return jsonify(user)
return jsonify({"error": "User not found"}), 404
# Create a new user
@app.route('/users', methods=['POST'])
def create_user():
new_user = request.get_json()
new_user['id'] = len(users) + 1
users.append(new_user)
return jsonify(new_user), 201
# Update an existing user
@app.route('/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
user = next((u for u in users if u['id'] == user_id), None)
if user:
data = request.get_json()
user.update(data)
return jsonify(user)
return jsonify({"error": "User not found"}), 404
# Delete a user
@app.route('/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
global users
users = [u for u in users if u['id'] != user_id]
return '', 204
if __name__ == '__main__':
app.run(debug=True)
Step 6: Test the REST API
To test the API, run the Flask application:
python app.py
Flask will start the development server, and you can access the API endpoints using tools like curl or Postman.
Output:
* Serving Flask app 'app'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
* Restarting with stat
* Debugger is active!
* Debugger PIN: 117-628-815
Example API Requests:
Get all users:
curl http://127.0.0.1:5000/users
Output:
[
{
"id": 1,
"name": "Alice"
},
{
"id": 2,
"name": "Bob"
},
{
"id": 3,
"name": "Charlie"
}
]
Get a user by ID:
curl http://127.0.0.1:5000/users/1
Output:
{
"id": 1,
"name": "Alice"
}
Create a new user:
curl -X POST -H "Content-Type: application/json" -d '{"name": "Dave"}' http://127.0.0.1:5000/users
Output:
{
"id": 4,
"name": "Dave"
}
Update an existing user:
curl -X PUT -H "Content-Type: application/json" -d '{"name": "David"}' http://127.0.0.1:5000/users/4
Output:
{
"id": 4,
"name": "David"
}
Delete a user:
curl -X DELETE http://127.0.0.1:5000/users/4
Step 7: Deploying the Flask Application
For production deployment, you shouldn't use Flask's built-in server. Instead, use a WSGI server like Gunicorn. Install Gunicorn:
pip install gunicorn
Then, run your Flask application with Gunicorn:
gunicorn --bind 0.0.0.0:8000 app:app
You can now access Flask API remotely. Add 8000
port in the firewall and access the API endpoints. You can also set up Nginx as a reverse proxy to handle client requests and forward them to Gunicorn.
Conclusion
You've created your first REST API with Flask on Ubuntu server.. This tutorial covered setting up a Python virtual environment, installing Flask, creating RESTful endpoints, and testing the API. With Flask's flexibility, you can easily extend this application to include more complex features and deploy it in a production environment.