s
API sWorld
Node.js
Python
Go
//API-REST var express = require('express'); var app = express(); //Repository var people = [ {"id":"1", "nombre":"Juan", "apellido":"Perez"}, {"id":"2", "nombre":"Ana", "apellido":"Lia"}, {"id":"3", "nombre":"Carlos", "apellido":"GarcĂa"} ]; //GET (People) app.get('/people', function(req, res){ res.send(people); }); //POST (Person) app.post('/people', function(req, res){ var id = req.body.id; var nombre = req.body.nombre; var apellido = req.body.apellido; people.push({"id": id, "nombre": nombre, "apellido": apellido}); res.send(people); }); //PUT (Person) app.put('/people/:personId', function(req, res){ var personId = req.params.personId; var nombre = req.body.nombre; var apellido = req.body.apellido; for(var x in people){ var person = people[x]; if(person.id === personId){ person.nombre = nombre; person.apellido = apellido; break; } } res.send(people); }); //DELETE (Person) app.delete('/people/:personId', function(req, res){ var personId = req.params.personId; for(var x in people){ var person = people[x]; if(person.id === personId){ people.splice(x, 1); break; } } res.send(people); }); //GET (Person) app.get('/people/:personId', function(req, res){ var personId = req.params.personId; var response = {"id":"0", "nombre":"Persona", "apellido":"Inexistente"}; for(var x in people){ var person = people[x]; if(person.id === personId){ response = person; break; } } res.send(response); }); //Port app.listen(8080);
Copy
Environment
## Install Node.js (PC) https://nodejs.org/es/download/ $ node -v ## Install Express (Project) $ npm install express
Run
$ node server.js
# API-REST from flask import Flask, jsonify, request app = Flask(__name__) # Repository products = [ {'name': 'laptop', 'price': 800, 'stock': 7}, {'name': 'mouse', 'price': 50, 'stock': 9}, {'name': 'monitor', 'price': 300, 'stock': 4} ] # Testing @app.route('/ping', methods=['GET']) def ping(): return jsonify({'response': 'pong'}) # GET (Routes) @app.route('/product') def getProducts(): return jsonify({'products': products}) # Create (Routes) @app.route('/product', methods=['POST']) def addProduct(): new_product = { 'name': request.json['name'], 'price': request.json['price'], 'stock': 10 } products.append(new_product) return jsonify({'products': products}) # Update (Route) @app.route('/product/<string:product_name>', methods=['PUT']) def editProduct(product_name): productsFound = [product for product in products if product['name'] == product_name] if (len(productsFound) > 0): productsFound[0]['name'] = request.json['name'] productsFound[0]['price'] = request.json['price'] productsFound[0]['stock'] = request.json['stock'] return jsonify({ 'message': 'Product Updated', 'product': productsFound[0] }) return jsonify({'message': 'Product Not found'}) # Remove (Route) @app.route('/product/<string:product_name>', methods=['DELETE']) def deleteProduct(product_name): productsFound = [product for product in products if product['name'] == product_name] if len(productsFound) > 0: products.remove(productsFound[0]) return jsonify({ 'message': 'Product Deleted', 'products': products }) # Get (Route) @app.route('/product/<string:product_name>') def getProduct(product_name): productsFound = [ product for product in products if product['name'] == product_name.lower()] if (len(productsFound) > 0): return jsonify({'product': productsFound[0]}) return jsonify({'message': 'Product Not found'}) # Port if __name__ == '__main__': app.run(debug=True, port=8080)
Copy
Environment
## Install Python (PC) https://www.python.org/downloads/ $ python ## Install Flask (PC) $ pip install Flask
Run
$ py server.py
package main import ( "encoding/json" "net/http" "strconv" "strings" ) type Person struct { ID string `json:"id,omitempty"` FirstName string `json:"firstname,omitempty"` LastName string `json:"lastname,omitempty"` Address *Address `json:"address,omitempty"` } type Address struct { Street string `json:"street,omitempty"` Number string `json:"number,omitempty"` } var people []Person func main() { // Repository people = append(people, Person{ID: "1", FirstName: "Julio", LastName: "Verne", Address: &Address{Street: "Gral. Paz", Number: "6655"}}) people = append(people, Person{ID: "2", FirstName: "Rosa", LastName: "Lia", Address: &Address{Street: "Catriel", Number: "1804"}}) people = append(people, Person{ID: "3", FirstName: "Lazy"}) // Routes http.HandleFunc("/people", peopleHandler) http.HandleFunc("/people/", personHandler) // Port http.ListenAndServe(":8080", nil) } // Handler /people (All) func peopleHandler(response http.ResponseWriter, request *http.Request) { switch request.Method { case "GET": getPeople(response) case "POST": createPerson(response, request) default: http.Error(response, "Method not allowed", http.StatusMethodNotAllowed) } } // Handler /people/{id} (Individual) func personHandler(response http.ResponseWriter, request *http.Request) { id := strings.TrimPrefix(request.URL.Path, "/people/") if id == "" { http.Error(response, "ID is required", http.StatusBadRequest) return } switch request.Method { case "GET": getPerson(response, id) case "PUT": updatePerson(response, request, id) case "DELETE": deletePerson(response, id) default: http.Error(response, "Method not allowed", http.StatusMethodNotAllowed) } } func getPeople(response http.ResponseWriter) { json.NewEncoder(response).Encode(people) } func createPerson(response http.ResponseWriter, request *http.Request) { var person Person _ = json.NewDecoder(request.Body).Decode(&person) person.ID = generateNewID() people = append(people, person) json.NewEncoder(response).Encode(person) } func updatePerson(response http.ResponseWriter, request *http.Request, id string) { var person Person _ = json.NewDecoder(request.Body).Decode(&person) for i, item := range people { if item.ID == id { people[i].FirstName = person.FirstName people[i].LastName = person.LastName people[i].Address = person.Address json.NewEncoder(response).Encode(people[i]) return } } http.Error(response, "Person not found", http.StatusNotFound) } func deletePerson(response http.ResponseWriter, id string) { for index, item := range people { if item.ID == id { people = append(people[:index], people[index+1:]...) json.NewEncoder(response).Encode(people) return } } http.Error(response, "Person not found", http.StatusNotFound) } func getPerson(response http.ResponseWriter, id string) { for _, item := range people { if item.ID == id { json.NewEncoder(response).Encode(item) return } } http.Error(response, "Person not found", http.StatusNotFound) } // Generate a new unique ID func generateNewID() string { return strconv.Itoa(len(people) + 1) }
Copy
Environment
## Install Go (PC) https://golang.org/dl/ $ go version
Build & Run
$ go build server.go $ go run server.go
GET
curl --location 'http://localhost:8080/people'
curl --location 'http://localhost:8080/people/1'
POST
curl --location 'http://localhost:8080/people' \ --header 'Content-Type: application/json' \ --data '{ "firstname": "Lisandro", "lastname": "Lopez", "address": { "street": "Av. Mitre", "number": "22" } }'
PUT
curl --location --request PUT 'http://localhost:8080/people/4' \ --header 'Content-Type: application/json' \ --data '{ "firstname": "Lisandro", "lastname": "Lopez", "address": { "street": "Av. Mitre", "number": "15" } }'
DELETE
curl --location --request DELETE 'http://localhost:8080/people/4'