Backend Languages: Code Examples and Explanation
JavaScript (Node.js + Express):
const express = require('express');
const app = express();
app.get('/users', (req, res) => {
res.json([{ id: 1, name: 'Alice' }]);
});
app.listen(3000, () => console.log('Server running on port 3000'));
Explanation: Sets up a web server using Express. Defines a GET route '/users' that returns a JSON
array. Node.js is great for real-time applications.
Python (Flask):
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/users')
def get_users():
return jsonify([{"id": 1, "name": "Alice"}])
app.run(port=3000)
Explanation: Flask is a micro-framework. This creates a '/users' route that returns a JSON response.
Python is easy to learn and widely used.
Java (Spring Boot):
@RestController
public class UserController {
@GetMapping("/users")
public List<Map<String, Object>> getUsers() {
Map<String, Object> user = new HashMap<>();
user.put("id", 1);
user.put("name", "Alice");
return List.of(user);
}
}
Explanation: Spring Boot is a Java framework used for enterprise-level applications. This sets up a
REST endpoint that returns a user list.
PHP (Laravel):
// routes/web.php
Route::get('/users', function () {
return response()->json([
['id' => 1, 'name' => 'Alice']
]);
});
Explanation: Laravel simplifies web development in PHP. This code returns JSON data from the
'/users' route.
Ruby (Rails):
# config/routes.rb
get '/users', to: 'users#index'
# app/controllers/users_controller.rb
class UsersController < ApplicationController
def index
render json: [{ id: 1, name: "Alice" }]
end
end
Explanation: Ruby on Rails emphasizes convention over configuration. This sets up a '/users' route
returning JSON data.
Go (Golang):
package main
import (
"encoding/json"
"net/http"
)
func usersHandler(w http.ResponseWriter, r *http.Request) {
users := []map[string]interface{}{
{"id": 1, "name": "Alice"},
}
json.NewEncoder(w).Encode(users)
}
func main() {
http.HandleFunc("/users", usersHandler)
http.ListenAndServe(":3000", nil)
}
Explanation: Go is a compiled language, great for performance. This example shows a basic server
with a '/users' endpoint.
Rust (Actix Web):
use actix_web::{get, web, App, HttpServer, Responder};
#[get("/users")]
async fn get_users() -> impl Responder {
web::Json(vec![serde_json::json!({"id": 1, "name": "Alice"})])
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(get_users))
.bind("127.0.0.1:3000")?
.run()
.await
}
Explanation: Rust provides safety and speed. Actix Web is a fast, powerful framework for building
web services.
C# (ASP.NET Core):
app.MapGet("/users", () => new[] {
new { id = 1, name = "Alice" }
});
Explanation: ASP.NET Core is used in the Microsoft ecosystem. This sets up a minimal API
endpoint returning JSON.