Tutorials  /  Python

How To Create a REST API with Flask on Ubuntu – Step-by-Step Guide

Ccentron Redaktion · March 2025 ·7 min read ·Python, Tutorial

In this tutorial, you will learn how to create a simple REST API using Flask, a lightweight Python web framework. We’ll cover the basics of setting up a Flask application, defining routes, handling requests, and returning JSON responses. By the end of this tutorial, you will have a working API that you can extend and integrate with other applications.

Prerequisites

  • A server running Ubuntu and a non-root user with sudo privileges and an active firewall. Please ensure to work with a supported version of Ubuntu.
  • Familiarity with the Linux command line.
  • A basic understanding of Python programming.
  • Python 3.7 or higher installed on your Ubuntu system.
VM

Matching infrastructure at centron

Scripts and services eventually need an environment that keeps running: ccloud³ VMs from €3.12 per month, billed by the hour. Rent a cloud server →

Step 1 — Setting Up Your Flask Environment

Ubuntu 24.04 ships Python 3 by default. Open the terminal and run the following command to double-check the Python 3 installation:

Code
root@ubuntu:~# python3 --version
Python 3.12.3

If Python 3 is already installed on your machine, the above command will return the current version of Python 3 installation. In case it is not installed, you can run the following command and get the Python 3 installation:

Code
root@ubuntu:~# sudo apt install python3

Next, you need to install the pip package installer on your system:

Code
root@ubuntu:~# sudo apt install python3-pip

Once pip is installed, let’s install Flask.

You will install Flask via pip. It’s recommended to do this in a virtual environment to avoid conflicts with other packages on your system.

Code
root@ubuntu:~# python3 -m venv myprojectenv
root@ubuntu:~# source myprojectenv/bin/activate
root@ubuntu:~# pip install Flask

Step 2 - Create a Flask Application

The next step is to write the Python code for the Flask application. To create a new script, navigate to your directory of choice:

Code
root@ubuntu:~# cd ~/path-to-your-script-directory

When inside the directory, create a new Python file, app.py, and import Flask. Then, initialize a Flask application and create a basic route.

Code
root@ubuntu:~# nano app.py

This will open up a blank text editor. Write your logic here or copy the following code:

Python
app.py
from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/')
def hello_world():
    return jsonify(message="Hello, World!")

# In-memory data store
items = [{"id": 1, "name": "This is item 1"}, {"id": 2, "name": "This is item 2"}]

Step 3 — Creating RESTful Routes

In this section, we’ll define routes in our Flask application that correspond to the different actions a user can perform on the API. Each route will handle a specific HTTP method.

GET, POST, PUT, and DELETE. These methods correspond to the four basic operations of persistent storage—often referred to as CRUD (Create, Read, Update, Delete).

Add the following routes to your app.py Python script:

Python
app.py
from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/')
def hello_world():
    return jsonify(message="Hello, World!")

# In-memory data store
items = [{"id": 1, "name": "This is item 1"}, {"id": 2, "name": "This is item 2"}]

# GET request: Retrieve all items
@app.route('/api/items', methods=['GET'])
def get_items():
    return jsonify(items)

# GET request: Retrieve a specific item by ID
@app.route('/api/items/', methods=['GET'])
def get_item(item_id):
    item = next((item for item in items if item["id"] == item_id), None)
    if item is None:
        return jsonify({"error": "Item not found"}), 404
    return jsonify(item)

# POST request: Create a new item
@app.route('/api/items', methods=['POST'])
def create_item():
    new_item = {"id": len(items) + 1, "name": request.json.get('name')}
    items.append(new_item)
    return jsonify(new_item), 201

# PUT request: Update an existing item
@app.route('/api/items/', methods=['PUT'])
def update_item(item_id):
    item = next((item for item in items if item["id"] == item_id), None)
    if item is None:
        return jsonify({"error": "Item not found"}), 404
    item['name'] = request.json.get('name', item['name'])
    return jsonify(item)

# DELETE request: Delete an item
@app.route('/api/items/', methods=['DELETE'])
def delete_item(item_id):
    global items
    items = [item for item in items if item["id"] != item_id]
    return '', 204

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

Let’s know more about what each function does:

Flask Imports

The code imports necessary components from Flask: Flask, jsonify, and request.

In-Memory Data Store

items is a simple list of dictionaries that acts as a temporary data store for the API. Each item has an id and a name.

GET /api/items

When a GET request is made to /api/items, the server returns a list of all items in the items data store. This is useful for retrieving all resources in a collection.

POST /api/items

A POST request to /api/items allows the client to create a new item. The server expects a JSON object containing the new item’s details in the request body. After creating the item, the server responds with the newly created item and a 201 Created status code.

PUT /api/items/<int:item_id>

A PUT request to /api/items/<item_id> is used to update an existing item with the specified item_id. The client sends the updated data in the request body, and the server modifies the existing item. If the item is not found, the server returns a 404 Not Found error.

DELETE /api/items/<int:item_id>

A DELETE request to /api/items/<item_id> removes the item with the specified item_id from the data store. If the item is successfully deleted, the server responds with a 204 No Content status code, indicating that the deletion was successful and there is no further content to return.

Running the Application

The if __name__ == "__main__": block ensures that the Flask application runs when the script is executed directly.

Step 4 — Running and Testing Your API

Start your Flask server using the following command:

Code
root@ubuntu:~# python3 app.py

You should notice the Flask server running with the below output:

Code
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: 837-877-972

Now, you can test the endpoints using curl, Postman, or another HTTP client. In this tutorial you will use curl to test the endpoints and send the HTTP requests.

Testing API Endpoints with curl

  • GET: curl http://127.0.0.1:5000/api/items
  • POST: curl -X POST -H "Content-Type: application/json" -d '{"name": "This is item 3"}' http://127.0.0.1:5000/api/items
  • PUT: curl -X PUT -H "Content-Type: application/json" -d '{"name": "This is updated item 1"}' http://127.0.0.1:5000/api/items/1
  • DELETE: curl -X DELETE http://127.0.0.1:5000/api/items/1

Example output after running the GET request:

Code
[
  {
    "id": 1,
    "name": "This is item 1"
  },
  {
    "id": 2,
    "name": "This is item 2"
  }
]

You will notice that the server returns a list of all items in the items data store.

Using thePOSTmethod, let’s add a new item to the datastore.

Code
root@ubuntu:~# curl -X POST -H "Content-Type: application/json" -d '{"name": "This is item 3"}' http://127.0.0.1:5000/api/items

Output

JSON
{
  "id": 3,
  "name": "This is item 3"
}

Note: On your other console where your Flask server is running, you will notice all the HTTP requests being executed and their response codes too.

Code
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 837-877-972
127.0.0.1 - - [23/Aug/2024 06:57:27] "GET /api/items HTTP/1.1" 200 -
127.0.0.1 - - [23/Aug/2024 06:59:56] "POST /api/items HTTP/1.1" 201 -

This is a great way to monitor, debug, and troubleshoot any issues with the server.

PUT Request: Updating an Existing Item

A PUT request to /api/items/<item_id> will update an existing item with the specified item_id.

Code
root@ubuntu:~# curl -X PUT -H "Content-Type: application/json" -d '{"name": "This is updated item 1"}' http://127.0.0.1:5000/api/items/1

Output

JSON
{
  "id": 1,
  "name": "This is updated item 1"
}

GET Request: Retrieving an Updated Item

Now, let’s execute a GET request to see the updated item 1.

Code
root@ubuntu:~# curl http://127.0.0.1:5000/api/items/1

Output

JSON
{
  "id": 1,
  "name": "This is updated item 1"
}

DELETE Request: Deleting an Item

Finally, let’s execute a DELETE request to remove an item from the datastore.

Code
root@ubuntu:~# curl -X DELETE http://127.0.0.1:5000/api/items/1

This will delete item 1 from the data store.

Verifying Deletion with GET Request

To verify this, let’s execute another GET request.

Code
root@ubuntu:~# curl http://127.0.0.1:5000/api/items

Output

Code
[
  {
    "id": 2,
    "name": "This is item 2"
  },
  {
    "id": 3,
    "name": "This is item 3"
  }
]

You will notice that item 1 is no longer present and has been deleted permanently.

Conclusion

In this tutorial, you’ve built a basic REST API app using Flask. You can now extend this API with additional routes, integrate with a database, or deploy it to a cloud platform. Flask is a powerful tool for building APIs quickly and efficiently, and with these basics, you’re ready to start building more complex applications.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren