This lesson connects a React UI to a Flask backend API for an image optimizer application.
In this lesson, we will connect the React UI to the Flask backend API of our image optimizer application. With both the backend and frontend already developed, it’s now time to integrate them for a seamless user experience.
Begin by navigating to your image optimizer application directory and activating your virtual environment. After that, start your Flask application with the following commands:
Copy
Ask AI
jeremy@Jeremys-Mac-Studio imageoptimizer.app % ls__pycache__ requirements.txt venv run.py(venv) jeremy@Jeremys-Mac-Studio imageoptimizer.app % flask run * Serving Flask app 'run.py' * Debug mode: offWARN:werkzeug:WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on https://127.0.0.1:5173/ (Press CTRL+C to quit)Nov/2024 14:19:371 "POST /upload HTTP/1.1" 200 -Nov/2024 14:19:421 "POST /upload HTTP/1.1" 200 -
For testing purposes, you can use Postman to verify that your API is running correctly.
With the backend active, it’s time to connect it with your React application.
Within your React app, update the API endpoint so that it correctly points to your Flask backend. Below is the core functionality for image uploading through React:
In this React component, the selected image is uploaded to the Flask backend. Upon a successful API response, the returned binary data is converted into an object URL for display. Both the original and optimized images are shown along with their respective file sizes for easy comparison.
When testing your application, open your browser’s developer tools to monitor network activity and validate that the Flask server is accessible at 127.0.0.1:5000. For instance, after choosing an image like “coolgirl.jpeg” from your computer, you should see a preview similar to the one below:
When running the React app and Flask API on separate ports, you might experience CORS errors. To resolve this, install Flask-Cors in your virtual environment:
Displaying Optimized Images and File Size Comparison
A major feature of this project is the display of both the original and optimized images, including their file sizes, for side-by-side comparison. Once you click the “Optimize Image” button, the React component processes the binary response from the Flask endpoint and displays the optimized image with its size information. For example:
In some cases, an initial image (e.g., 85.95 kilobytes) might be optimized to 24.94 kilobytes, resulting in a 71% size reduction. Experiment with various quality settings to see how they affect the file size and visual quality.