Building a Simple File Upload and Download REST API with Flask

Most modern web applications support uploading and downloading files. Whether you're updating your profile picture, uploading documents, or downloading reports, handling files is a must-have feature.

In this article,  we’ll explore how to build a File Upload and Download API using Python and Flask, a lightweight web framework that's perfect for beginners and small projects.


Step 1: Set Up Your Project Environment

Before writing any code, make sure Flask is installed on your system.

pip install flask

Create a new file named app.py. This will be your main application file.


Step 2: Create a Basic Flask App Structure

Let’s start with the foundational setup of a Flask app.

from flask import Flask, request, send_from_directory  # Import necessary Flask modules
import os  # Import os for file system operations

app = Flask(__name__)  # Initialize the Flask app

# Define a folder where uploaded files will be stored
UPLOAD_FOLDER = 'uploads'

# Create the uploads directory if it doesn't already exist
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

# Configure the upload folder path in the Flask app
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

Explanation:

  • send_from_directory helps serve files safely.
  • os.makedirs(..., exist_ok=True) ensures the folder is created once, avoiding errors.

Step 3: Implement the File Upload API

Let’s create a route to handle file uploads.

@app.route('/upload', methods=['POST'])
def upload_file():
    # Check if 'file' is part of the request
    if 'file' not in request.files:
        return {'message': 'No file part in the request'}, 400

    file = request.files['file']

    # If no file is selected
    if file.filename == '':
        return {'message': 'No selected file'}, 400

    # Create the full path to save the file
    filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)

    # Save the file to the specified path
    file.save(filepath)

    return {'message': 'File uploaded successfully'}, 200

How to Test the Upload Endpoint

  • Use Postman, Insomnia, curl, or a custom frontend.
  • Send a POST request to http://localhost:5000/upload with a form-data key named file.

Step 4: Implement the File Download API

Now, let’s create an endpoint that serves files for downloading.

@app.route('/download/<filename>', methods=['GET'])
def download_file(filename):
    # Serve the file from the upload directory
    # as_attachment=True tells the browser to download it
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)

How to Use the Download Endpoint

  • Access http://localhost:5000/download/yourfile.jpg in your browser.
  • The file will automatically download if it exists in the upload folder.

Step 5: Run Your Flask App

Now, let’s set up the main entry point of the app:

if __name__ == '__main__':
    # Run the Flask app in debug mode (helps during development)
    app.run(debug=True)

How to Start the App

Open your terminal and run:

python app.py

Navigate to http://localhost:5000 in your browser or API client, and test the /upload and /download/<filename> routes.


Next Steps & Best Practices

While the app works, here are some things you can add to make it production-ready:

  • File type validation: Only allow certain types (e.g., .jpg, .pdf, etc.).
  • Size limits: Prevent very large files from being uploaded.
  • Authentication: Secure the upload and download endpoints.
  • Cloud storage: Store files in platforms like AWS S3, Google Cloud, or Azure for scalability.

Testing The Api

On an Ubuntu 24.04 running inside android with proot, I start the app.py on  termina1




And then navigates to the upload and download routes on a terminal2 with curl


Conclusion

This is a simple, but fully functional file upload and download API using Flask.

This project is a great starting point to understand:

  • HTTP methods (POST, GET)
  • Handling file data
  • Using Flask routes and configurations

As you grow more comfortable, try integrating this into a full-stack web app or connect it to a database for file metadata storage.




Comments

Popular posts from this blog

Securely Access Remote Machines with SSH

The Church as the Expression of the Triune God