REST API with Express.js
Static API Example
Tehdään REST API sovellus, jossa ei käytetä tietokantaa, vaan data on staattisessa arrayssä, kuten aiemmissa esimerkeissä.
  1. Luo kansio nimeltään staticExample
  2. Kopio expressExamplen tiedostot package.json ja app.js kansioon staticExample ja avaa komentohekote kansioon
  3. Anna komento npm install
  4. Käynnistä sovellus komennolla nodemon app.js
  5. Lisää sovellukseen kansiot routes ja models
  6. Lisää routes kansioon tiedosto book.js ja siihen rivit
    const express = require('express');
    const router = express.Router();
    
    module.exports=router
    
  7. Lisää tiedostoon metodit
    • router.get('/')
    • router.get('/:id')
    • router.post('/')
    • router.put('/:id')
    • router.delete('/:id')
  8. Laita kuhunkin metodiin jokin teksti, jonka response palauttaa
  9. Muokkaa app.js niin, että sovelluksesta löytyy endpoint http://localhost:3000/book
  10. Testaa kaikki metodit Postmanilla
  11. Lisää sitten models kansioon tiedosto book_model.js. Määritä tiedostossa objekti book, jossa:
    • bookArray
    • metodit kullekin book-controllerin metodille
    • esimerkiksi getAllBooks-metodi ottaa argumenttina funktion callback ja kutsuu tuota metodia argumenttina bookArray
    • eksporttaa objekti book
  12. Muuta sitten book-controlleria, niin että
    • Määritä objekti book, joka saadaan modelista
    • Muuta router.get kutsumaan modelin getAllBooks metodia argumenttina seuraava anonyymi funktio
          function(result){
              response.json(result);
          }
          
  13. Testaa sovelluksen toimintaa ja muuta muutkin metodit

Esimerkin tarkoitus

Esimerkissä ei käytetä tietokantaa, jotta huomio keskittyisi controller-model tomintaan ja callbackien toimintaan. Sovelluksessa http-pyynnöt ottaa vastaan book-controller. Book-controller kutsuu book_modelin funktiota, jolle se antaa argumenttina seuraavaa:
  • Aina anonyymin funktion, joka aikanaan lähettää responsena model-funktion luoman datan
  • Mahdollisesti uuden tai muokattavan kirjan tiedot (request.body)
  • Mahdollisesti kirjan id:n (request.params.id)
Book_modelin funktio tekee toimenpiteet (etsii, lisää, muokkaa, poistaa) ja asettaa sovitun datan callback-metodiin argumentiksi. Nyt kuitenkaan modelissa ei oikeasti kutsuta asynkroonisia funktioita, joten tässä ei tarvitsisi käyttää callbackeja. Kuitenkin sitten, kun data on tietokannassa, funktiot ovat asynkronisia ja callbackit ovat välttämättömiä.
We will create a REST API application without using a database. Instead, the data will be stored in a static array, similar to previous examples.
  1. Create a folder named staticExample.
  2. Copy the package.json and app.js files from the expressExample project into the staticExample folder and open a command prompt in the folder.
  3. Run the command:
    npm install
  4. Start the application with:
    nodemon app.js
  5. Add two new folders to the project: routes and models.
  6. Inside the routes folder, create a file named book.js and add the following lines:
     const express = require('express'); const router = express.Router();
    module.exports = router; 
  7. Add the following methods to the file:
    • router.get('/')
    • router.get('/:id')
    • router.post('/')
    • router.put('/:id')
    • router.delete('/:id')
  8. Add a response message in each method to return a simple text response.
  9. Modify app.js so that the application includes an endpoint at:
    http://localhost:3000/book
  10. Test all the methods using Postman.
  11. Inside the models folder, create a file named book_model.js. In this file, define an object book containing:
    • A bookArray to store book data.
    • Methods corresponding to each book-controller method.
    • For example, the getAllBooks method should take a callback function as an argument and call that function with bookArray as its argument.
    • Export the book object.
  12. Modify the book-controller so that:
    • Define a book object that is imported from the model.
    • Change router.get to call the model's getAllBooks method, passing in the following anonymous function:
       function(result){ response.json(result); } 
  13. Test the application and modify the remaining methods accordingly.

Purpose of the Example

This example does not use a database so that the focus remains on the controller-model structure and the use of callbacks. In the application, HTTP requests are handled by the book-controller. The book-controller calls functions from book_model, passing in the following arguments:
  • Always an anonymous function that will eventually return the response containing the data from the model function.
  • Possibly the details of a new or updated book (**request.body**).
  • Possibly the book ID (**request.params.id**).
The functions in book_model perform the necessary operations (searching, adding, updating, deleting) and pass the appropriate data to the callback function as an argument. Although in this example, the model does not actually call asynchronous functions, callbacks are still used to demonstrate their necessity. Once data is stored in a database, the functions will be asynchronous, and callbacks (or promises/async-await) will be essential.



Toggle Menu