Suggestions

TLDR; Not Your Typical Privacy Agreement

Powered by Cohere

Samsung Galaxy S10e

Specifications

  • Dimensions: 142.2 x 69.9 x 7.9 mm (5.60 x 2.75 x 0.31 in)
  • Weight: 150 g (5.29 oz)
  • Display: Dynamic AMOLED, HDR10+
  • Resolution: 1080 x 2280 pixels, 19:9 ratio (~438 ppi density)
  • OS: Android 9.0 (Pie), upgradable to Android 12, One UI 4.1
  • CPU: Octa-core (2x2.73 GHz Mongoose M4 & 2x2.31 GHz Cortex-A75 & 4x1.95 GHz Cortex-A55) - EMEA/LATAM
  • Main Camera: 12 MP, f/1.5-2.4, 26mm (wide)
  • Selfie Camera: 10 MP, f/1.9, 26mm (wide), 1/3", 1.22µm, dual pixel PDAF
  • Battery: Li-Ion 3100 mAh, non-removable
All Notes

Creating a REST API (PHP vs JavaScript vs Python)

Thursday, March 27, 2025
Author:
Share to Reddit
Share to Facebook
Share to X
Share to LinkedIn
Share to WhatsApp
Share by email
Describing the associated blog post


You may skip directly to any of the main sections using the links below:

I have heard this before. Backend development is like being a Chef in a restaurant👨‍🍳. The customers do not see you, but your work impacts the entire business. You rely solely on Frontend Developers (Managers), and HTTP requests (Waiters) to respond to client requests.

This article explores how to get started with creating RESTful services using three programming languages, JavaScript, Python, and PHP, using their respective frameworks, Express, Django, and Laravel. It demonstrates a minimal setup to implement HTTP requests to the server and get a response.

Setting Up the Node.js Backend

To successfully create a Node.js backend, Node.js and npm must be installed on the system. The first step is to initialize the Node.js project. Refer to this article about installing Express.js for instructions on how to do this. We can then run the following command to install our dependencies.

npm install express body-parser cors

Once the Node.js environment is setup, we can create a file in the root of the project and name it server.js or anything you prefer.

server.js:

const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ limit: "50mb", extended: false }));
app.use(cors()); // CORS = Cross Origin Resource Sharing

// Defining a GET request
app.get("/node-app", async(req, res) => {
    setTimeout(() => {
        res.status(200).send({
            message: "Successful GET request"
        })
    }, 4000);
});

// Defining a POST request
app.post("/node-app", async(req, res) => {
    try{
        setTimeout(() => {
            res.status(200).send({
                message: "Successful POST request"
            })
        }, 4000);
    } catch(error){
        res.status(500).send({
            message: "An error has occurred"
        })
    }
});

// Defining a PUT request
app.put("/node-app/:id", async(req, res) => {
    try{
        const ID = req.params.id;

        setTimeout(() => {
            res.status(200).send({
                message: `Successful PUT request for ID: ${ID}`
            })
        }, 4000);
    } catch(error){
        res.status(500).send({
            message: "An error has occurred"
        })
    }
});

// Defining a DELETE request
app.delete("/node-app/:id", async(req, res) => {
    try{
        const ID = req.params.id;

        setTimeout(() => {
            res.status(200).send({
                message: `Successful DELETE request for ID: ${ID}`
            })
        }, 4000);
    } catch(error){
        res.status(500).send({
            message: "An error has occurred"
        })
    }
});

const port = 8000;
app.listen(port, () => {
    console.log(`Server running on port http://localhost:${port}`)
});

You will notice the use of the setTimeout() function in each of the above HTTP requests. This simulates a database or asynchronous operation via a 4-second delay. We then need to ensure that the package.json file has a script that will run our application.

...
"main": "server.js",
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
...

The file name used in the script needs to match the name of the file containing the code. Running the npm run start command will start the application and write the port to the terminal. We can test using the endpoints using a tool like Postman or even a client application such as a browser. All requests to 'http://localhost:8000/node-app' will provide a relevant response. And that's that it! We have a simple Node.js server to take care of all our requests 😎.

I decided to go with Node.js first because it is the backend framework I have the most experience with and enjoy working with the most, nothing personal.

Setting Up the Django Backend

In this section, we will set up a minimal REST API server using Django without a database. We will demonstrate how to handle GET, POST, PUT, and DELETE requests using Django's built-in HTTP response utilities and Django REST framework.

Prerequisites

Ensure you have Python installed on your computer. You can download and install it from the official Python website.

Setting Up the Django Project

To create a Django project, open your terminal and run the following commands sequentially:

Step 1: Create the Project Directory:

mkdir django-app && cd django-app

Step 2: Set Up a Virtual Environment:

python -m venv venv

Step 3: Activate the Virtual Environment (Works on Windows only):

venv\Scripts\activate

Step 4: Install Dependencies:

pip install django djangorestframework django-cors-headers

Step 5: Create a Django Project and App:

django-admin startproject backend .
django-admin startapp app

Configure settings.py

Open backend/settings.py and update the following:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'app',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'corsheaders.middleware.CorsMiddleware',  # Enable CORS
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",  # Adjust based on your frontend application
]

DATABASES = {
    'default': {}  # No database needed
}

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ]
}

Configure API Routes

Step 1: Create API Views:

Open app/views.py and define the API views:

from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json

def index(request):
    return JsonResponse({"message": "Successful Python API response"}, status=200)

def details(request, ID):
    if request.method == 'GET':
        return JsonResponse({"message": f"Python GET request for resource {ID} was successful!"}, status=200)

    return HttpResponse(status=405)  # Method Not Allowed

@csrf_exempt
def create_resource(request):
    if request.method == 'POST':
        try:
            return JsonResponse({"message": "Successful Python POST request"}, status=201)
        except json.JSONDecodeError:
            return JsonResponse({"error": "Invalid JSON data"}, status=400)

    return HttpResponse(status=405)

@csrf_exempt
def update_resource(request, ID):
    if request.method == 'PUT':
        return JsonResponse({"message": f"Resource {ID} updated successfully!"}, status=200)

    return HttpResponse(status=405)

@csrf_exempt
def delete_resource(request, ID):
    if request.method == 'DELETE':
        return JsonResponse({"message": f"Resource {ID} deleted successfully!"}, status=200)

    return HttpResponse(status=405)

Step 2: Define URL Patterns:

Open app/urls.py and set up the routing for the API:

from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from .views import index, details, create_resource, update_resource, delete_resource

urlpatterns = [
    path('', index, name='home'),
    path('details/<int:ID>/', details, name='details'),
    path('create/', create_resource, name='create'),
    path('update/<int:ID>/', update_resource, name='update'),
    path('delete/<int:ID>/', delete_resource, name='delete'),
]

urlpatterns = format_suffix_patterns(urlpatterns)

Step 3: Include API URLs in backend/urls.py:

Open backend/urls.py and update it as follows:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('django-app/', include('app.urls')),
]

Running the Server

Now, run the Django development server:

python manage.py runserver

The API will be available at http://127.0.0.1:8000/django-app/.

Testing API Endpoints

You can test the API using Postman, cURL, or your frontend.

1. GET Request

curl -X GET http://127.0.0.1:8000/django-app/details/1/

Response:

{
  "message": "Python GET request for resource 1 was successful!"
}

2. POST Request

curl -X POST http://127.0.0.1:8000/django-app/create/

Response:

{
  "message": "Successful Python POST request"
}

3. PUT Request

curl -X PUT http://127.0.0.1:8000/django-app/update/1/

Response:

{
  "message": "Resource 1 updated successfully!"
}

4. DELETE Request

curl -X DELETE http://127.0.0.1:8000/django-app/delete/1/

Response:

{
  "message": "Resource 1 deleted successfully!"
}

We have successfully set up a minimal Django REST API server that handles GET, POST, PUT, and DELETE requests. This setup is ideal for lightweight applications or mock APIs without requiring a database.

Setting Up the Laravel Backend

To work with Laravel, PHP must be installed on the system. Refer to this article for instructions on how to install PHP. Composer should also be installed. This is a package manager for PHP similar to npm. Installation instructions can be found on the official website.

Starting the Laravel Project

To initiate a Laravel project, execute the following command:

composer create-project laravel/laravel laravel-app

In the command above, "laravel-app" is the name of the project, but you can choose any name. Once the command has finished executing, navigate into the project folder:

cd laravel-app

Laravel provides a built-in development server. You can start it by running:

php artisan serve

This will start the server, and you should see output indicating that the application is running at http://127.0.0.1:8000. Opening this URL in a browser will display the default Laravel welcome page.

Laravel Default Folder Structure

After creating a new Laravel application, the project folder will include the following key directories:

Folder Description
app Contains the core application logic, including HTTP controllers and models.
bootstrap Holds the application bootstrapping scripts.
config Stores configuration files for services like database, caching, authentication, and application settings.
database Contains migrations, factories, and seeders for database interactions.
public The entry point of the application (contains index.php and assets like images and JavaScript files).
resources Contains view templates, CSS, and JavaScript files. The views folder has .blade.php files for templating.
routes Defines application routes. The main files are web.php (for web routes) and api.php (for API routes).
storage Stores logs, file uploads, and compiled views.
tests Contains unit and feature tests.
vendor Holds dependencies installed via Composer.

In the project root, you’ll also find other configuration files such as package.json, composer.lock, and artisan.

Creating API Routes

To set up API routes, generate a new controller:

php artisan make:controller ApiController

This command creates a new file in app/Http/Controllers/ called ApiController.php. Next, define API routes inside routes/api.php:

<?php

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

Route::prefix('/laravel-app')->group(function () {
    Route::get('/', [ApiController::class, 'index']);
    Route::get('/{id}', [ApiController::class, 'show']);
    Route::post('/', [ApiController::class, 'store']);
    Route::put('/{id}', [ApiController::class, 'update']);
    Route::delete('/{id}', [ApiController::class, 'destroy']);
});

Running the Server

Run the following command to start the server:

php artisan serve

With this setup, you can successfully send GET, POST, PUT, and DELETE requests to http://127.0.0.1:8000/api/laravel-app.

Testing the API

To test the API endpoints, you can use tools like Postman or cURL commands:

GET request:

curl -X GET http://127.0.0.1:8000/api/laravel-app

POST request:

curl -X POST http://127.0.0.1:8000/api/laravel-app -H "Content-Type: application/json"

PUT request:

curl -X PUT http://127.0.0.1:8000/api/laravel-app/1 -H "Content-Type: application/json"

DELETE request:

curl -X DELETE http://127.0.0.1:8000/api/laravel-app/1

With this setup, the Laravel API is ready to handle basic CRUD operations!

Conclustion

The three programming languages used in this article are the ones I've worked with to build backends for actual projects. Most of the projects I've worked on use Node.js as you can see if you navigate to the projects page of this website.

When I started programming, I was intimidated by and didn't like working on the server-side. I always, and still do to some extent, have had a phobia of working with real-world data especially because real people rely on it. But I guess like a doctor, people rely on you to solve the problem. I hope you've derived value from this article.

Tawanda Andrew Msengezi

Tawanda Andrew Msengezi is a Software Engineer and Technical Writer who writes all the articles on this blog. He has a Bachelor of Science in Computer Information Systems from Near East University. He is an expert in all things web development with a specific focus on frontend development. This blog contains articles about HTML, CSS, JavaScript and various other tech related content.

User Notice

Dear Visitor,

This website stores your color theme preference, you can toggle your theme preference using the lightbulb icon in the top right of the webpage.

Clicking on the robot icon that says "Chat" in the bottom-left corner will open a chat with an AI assistant. Click the button below to close this message.