Building RESTful APIs with Laravel & Python

In this tutorial, I’ll guide you through creating a RESTful API using Laravel for managing the structure and endpoints while leveraging Python for handling complex backend processing. By combining Laravel’s simplicity with Python’s flexibility, we’ll develop a powerful, efficient API that can tackle demanding tasks in a straightforward way.

This approach enables you to use Laravel for routing and API structure while allowing Python to handle complex data processing, machine learning, or data analysis tasks.

Building RESTful APIs with Laravel & Python

Building RESTful APIs with Laravel & Python

 

Step 1: Set Up Your Laravel Project

First, ensure that you have Laravel installed. If not, install it using Composer:

composer create-project laravel/laravel laravel-python-api
cd laravel-python-api

In routes/api.php, define a route for calling the Python function.

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ApiController;

Route::get('/data-process', [ApiController::class, 'processData']);

 

Step 2: Set Up the Controller in Laravel

Run the following command to create an ApiController.

php artisan make:controller ApiController

In app/Http/Controllers/ApiController.php, set up a method that will make an HTTP request to the Python service.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class ApiController extends Controller
{
    public function processData()
    {
        // Send request to Python backend
        $response = Http::get('http://127.0.0.1:5000/process');

        return response()->json([
            'status' => 'success',
            'data' => $response->json(),
        ]);
    }
}

 

Step 3: Set Up the Python Backend with Flask

In your Python environment, install Flask.

pip install flask

In a new Python file (e.g., app.py), define a basic Flask application.

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/process', methods=['GET'])
def process_data():
    # Here, we can add complex data processing logic
    result = {"message": "Data processed successfully"}
    return jsonify(result)

if __name__ == '__main__':
    app.run(port=5000)

Start the Flask server.

python app.py

 

Step 4: Test the Integration

Start Laravel Server using the following command.

php artisan serve

Open your browser or use a tool like Postman to test the endpoint /api/data-process.

You should see the JSON response from the Python backend.

{
  "status": "success",
  "data": {
    "message": "Data processed successfully"
  }
}

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS