Setting up a Flask application on Ubuntu involves a few steps, including installing
Python and Flask, setting up your Flask application, and running it. Below is a basic
guide to get you started, followed by a simple Flask application example.
### Step 1: Install Python and Flask
1. Update Package List: Ensure your Ubuntu package list is updated.
sudo apt update
2. Install Python3 and pip: If you haven't installed Python3 and pip
(Python's package installer), install them.
sudo apt install python3 python3-pip
3. Install Flask: Use pip to install Flask.
pip3 install Flask
### Step 2: Create Your basic Flask Application
1. Create a Project Directory: Make a directory for your project and navigate
into it.
mkdir myflaskapp
cd myflaskapp
2. Create a Python File: Create a Python file for your application, e.g.,
`[Link]`.
vi [Link]
3. Add Sample Flask Code: Copy the following simple Flask application code into your
`[Link]` file.
python
from flask import Flask, jsonify
app = Flask(__name__)
@[Link]('/')
def hello_world():
return 'Hello, World!'
@[Link]('/api/data', methods=['GET'])
def get_data():
data = {"name": "Flask", "version": "1.1.2"}
return jsonify(data)
if __name__ == '__main__':
[Link](debug=True, host='[Link]', port=5000)
This code creates a basic Flask app with two routes: one that returns a "Hello, World!"
message, and another (`/api/data`) that returns some JSON data.
4. Save and Exit: Press `CTRL+X`, then `Y` to save changes, and `Enter` to exit the
nano editor.
### Step 3: Run Your Flask Application
Since the `[Link]()` method in your `[Link]` specifies the host and port, you can
also run your app directly with Python:
python3 [Link]
Now, your Flask application should be running on `[Link] You can
access it via any web browser by navigating to `[Link] or
`[Link]
Accessing `[Link] will display "Hello, World!", and accessing
`[Link] will return the JSON data.
create another Flask CRUD based Application
vi [Link]
from flask import Flask, request, jsonify
app = Flask(__name__)
# Simulated database of items
items = [
{"id": 1, "name": "Item 1", "description": "This is item 1"},
{"id": 2, "name": "Item 2", "description": "This is item 2"},
]
@[Link]('/')
def home():
return "Hello, Flask REST API!"
@[Link]('/items', methods=['GET'])
def get_items():
return jsonify(items)
@[Link]('/item/<int:item_id>', methods=['GET'])
def get_item(item_id):
item = next((item for item in items if item["id"] == item_id), None)
if item:
return jsonify(item)
else:
return jsonify({"message": "Item not found"}), 404
@[Link]('/item', methods=['POST'])
def create_item():
new_item = [Link]
new_item["id"] = items[-1]["id"] + 1 if items else 1
[Link](new_item)
return jsonify(new_item), 201
@[Link]('/item/<int:item_id>', methods=['PUT'])
def update_item(item_id):
item = next((item for item in items if item["id"] == item_id), None)
if item:
data = [Link]
[Link](data)
return jsonify(item)
else:
return jsonify({"message": "Item not found"}), 404
@[Link]('/item/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
global items
items = [item for item in items if item["id"] != item_id]
return jsonify({"message": "Item deleted"}), 200
if __name__ == '__main__':
[Link](debug=True, host='[Link]', port=5000)
This setup is ideal for development and testing. For production environments, you'll
want to consider additional steps for security, performance, and reliability, including
deploying your Flask app with a WSGI server like Gunicorn and using a web server like
Nginx as a reverse proxy.
Based on the provided Python Flask code, I'll give you examples of `curl` commands to
interact with this REST API. Each command corresponds to different endpoints and
operations defined in your Flask application.
### 1. Get All Items
This `curl` request fetches all items from the `/items` endpoint.
curl [Link]
### 2. Get a Specific Item
To fetch a specific item by its ID, replace `1` with the desired item ID in the
`/item/<item_id>` endpoint.
curl [Link]
### 3. Create a New Item
This `curl` request posts a new item to the `/item` endpoint. Replace the `name` and
`description` values with the details of the item you want to add.
curl -X POST [Link] \
-H "Content-Type: application/json" \
-d '{"name": "New Item", "description": "This is a new item"}'
### 4. Update an Existing Item
To update an existing item, you need to specify the item ID in the URL and provide the
updated name and/or description in the JSON payload. Replace `1` with the item ID
you wish to update.
curl -X PUT [Link] \
-H "Content-Type: application/json" \
-d '{"name": "Updated Item", "description": "This item has been updated"}'
### 5. Delete an Item
To delete an item, specify the item ID in the URL. Replace `1` with the item ID of the
item you wish to delete.
curl -X DELETE [Link]
Remember, for these `curl` commands to work, your Flask application needs to be
running. The application is configured to run on `localhost` (your machine) on port
`5000`, so make sure that port is available and not blocked by any firewall.