The purpose of this post is to show the following:
Here's our frontend. It's a simple HTML with a jQuery table plugin. You can run this on your browser
HTML / CSS / JavaScript
NODEJS / EXPRESS
JAVA / SPRING BOOT
GO / standard library
Python / Flask
PHP/ CodeIgniter
Note: I only pasted the controller and not the whole framework because it's gonna be too long
- Separation of frontend and backend concerns
- You can focus on UI contract without getting bogged down by the backend implementation
- The backend can be implemented in multiple languages and you can arrive at the same result
- Pick your poison and stick with it
- These are not the best implementations per language but the point is to give you a taste of what's possible
- Apparently the code tags in this forum is removing the whitespaces unfortunately
Here's our frontend. It's a simple HTML with a jQuery table plugin. You can run this on your browser
HTML / CSS / JavaScript
Code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Simple CRUD</title>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
</head>
<body style="width:80%; margin: 0 auto; margin-top: 20px">
<table id="mytable" class="display" >
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Hobby</th>
<th>Contact</th>
</tr>
</thead>
</table>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<script type="text/javascript">
$(document).ready( function () {
$('#mytable').DataTable({
ajax: 'http://localhost:8080/api/people',
columns: [
{ data: 'firstname' },
{ data: 'lastname' },
{ data: 'hobby' },
{ data: 'contact' }
]
});
});
</script>
</body>
</html>
NODEJS / EXPRESS
Code:
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser');
const app = express()
const PORT = 80
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.get('/api/people', function (req, res) {
console.log('Retrieving people ...');
const response = { data : retrievePeople() };
res.send(response);
});
app.listen(PORT, function () {
console.log('Example app listening on port ' + PORT + '!');
});
const retrievePeople = () => {
const people = [];
people.push({
firstname: 'John',
lastname: 'Smith',
hobby: 'tennis',
contact: 'johnsmith@mailinator.com'
});
people.push({
firstname: 'Jane',
lastname: 'Watson',
hobby: 'volleyball',
contact: 'janewatson@mailinator.com'
});
people.push({
firstname: 'Mike',
lastname: 'Myers',
hobby: 'basketball',
contact: 'mikemyers@mailinator.com'
});
return people;
};
JAVA / SPRING BOOT
Code:
package com.example.crud.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.example.crud.model.Person;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
@CrossOrigin
@Controller
@RequestMapping(path="/api")
public class PersonController {
@GetMapping(path="/people")
public @ResponseBody Map<String, List<Person>> all() {
Map<String, List<Person>> people = new HashMap<>();
people.put("data", listAll());
return people;
}
private List<Person> listAll() {
final Person john = Person.builder()
.firstname("John")
.lastname("Smith")
.hobby("tennis")
.contact("johnsmith@mailinator.com")
.build();
final Person jane = Person.builder()
.firstname("Jane")
.lastname("Watson")
.hobby("volleyball")
.contact("janewatson@mailinator.com")
.build();
final Person mike = Person.builder()
.firstname("Mike")
.lastname("Myers")
.hobby("basketball")
.contact("mikemyers@mailinator.com")
.build();
return Arrays.asList(john, jane, mike);
}
}
GO / standard library
Code:
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type Person struct {
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
Hobby string `json:"hobby"`
Contact string `json:"contact"`
}
type Response struct {
Persons []Person `json:"data"`
}
func main() {
http.HandleFunc("/api/people", func(w http.ResponseWriter, r *http.Request) {
setupResponse(&w, r)
if (*r).Method == "OPTIONS" {
return
}
profile := Response{ []Person {
Person{"John", "Smith", "tennis", "johnsmith@mailinator.com"},
Person{"Jane", "Watson", "volleyball", "janewatson@mailinator.com"},
Person{"Mike", "Myers", "basketball", "mikemyers@mailinator.com"},
}}
fmt.Println(profile)
js, err := json.Marshal(profile)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
})
http.ListenAndServe(":80", nil)
}
func setupResponse(w *http.ResponseWriter, req *http.Request) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
Python / Flask
Code:
from flask import Flask
from flask import jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/api/people')
def hello_whale():
return jsonify(get_people())
def get_people():
john = {
'firstname': 'John',
'lastname': 'Smith',
'hobby': 'tennis',
'contact': 'johnsmith@mailinator.com'
}
jane = {
'firstname': 'Jane',
'lastname': 'Watson',
'hobby': 'volleyball',
'contact': 'janewatson@mailinator.com'
}
mike = {
'firstname': 'Mike',
'lastname': 'Myers',
'hobby': 'basketball',
'contact': 'mikemyers@mailinator.com'
}
return { 'data': [john, jane, mike ]}
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
PHP/ CodeIgniter
Note: I only pasted the controller and not the whole framework because it's gonna be too long
Code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class People extends CI_Controller {
public function __construct($config = 'rest')
{
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
parent::__construct();
}
public function index()
{
$john = array(
'firstname' => 'John',
'lastname' => 'Smith',
'hobby' => 'tennis',
'contact' => 'johnsmith@mailinator.com');
$jane = array(
'firstname' => 'Jane',
'lastname' => 'Watson',
'hobby' => 'volleyball',
'contact' => 'janewatson@mailinator.com');
$mike = array(
'firstname' => 'Mike',
'lastname' => 'Myers',
'hobby' => 'basketball',
'contact' => 'mikemyers@mailinator.com');
$data = array('data' => array($john, $jane, $mike));
header('Content-Type: application/json');
echo json_encode( $data );
}
}
Attachments
-
You do not have permission to view the full content of this post. Log in or register now.