Vodič za REST API - REST klijent, REST usluga i API pozivi objašnjeni primjerima koda

Jeste li se ikad zapitali kako prijava / registracija na web mjestu funkcionira na pozadini? Ili kako kad tražite "slatke mace" na YouTubeu, dobijete gomilu rezultata i uspijete se strujati s udaljenog stroja?

U ovom priručniku za početnike provest ću vas kroz postupak postavljanja RESTful API-ja. Deklasificirat ćemo neke od žargona i pogledati kako možemo kodirati poslužitelj u NodeJS. Zaronimo malo dublje u JavaScript!

Makni taj žargon

Pa, što je REST? Prema Wikipediji:

Reprezentativni prijenos stanja ( REST ) softverski je arhitektonski stil koji definira skup ograničenja koja će se koristiti za stvaranje web usluga. RESTful web usluge omogućuju sustavima koji zahtijevaju pristup i manipuliranje tekstualnim prikazima web resursa korištenjem jedinstvenog i unaprijed definiranog skupa operacija bez državljanstva.

Demistificirajmo što to znači (nadamo se da ste dobili puni obrazac). REST je u osnovi skup pravila za komunikaciju između klijenta i poslužitelja. Postoji nekoliko ograničenja u definiciji REST-a:

  1. Klijent-poslužiteljska arhitektura : korisničko sučelje web stranice / aplikacije treba biti odvojeno od zahtjeva / pohrane podataka, tako da se svaki dio može prilagoditi pojedinačno.
  2. Apatridnost : komunikacija ne bi trebala imati kontekst klijenta pohranjen na poslužitelju. To znači da svaki zahtjev poslužitelju treba podnijeti sa svim potrebnim podacima i ne smiju se stvarati pretpostavke ako poslužitelj ima podatke iz prethodnih zahtjeva.
  3. Slojeviti sustav : klijent ne bi smio znati hoće li komunicirati izravno s poslužiteljem ili nekim posrednikom. Ovi posrednički poslužitelji (bilo proxy ili balanseri opterećenja) omogućuju skalabilnost i sigurnost osnovnog poslužitelja.

Dobro, sad kad znate što su RESTful usluge, evo nekih izraza koji se koriste u naslovu:

  1. Klijent REST : kôd ili aplikacija koja može pristupiti tim REST uslugama. Trenutno koristite jedan! Da, preglednik može djelovati kao nekontrolirani REST klijent (web mjesto obrađuje zahtjeve preglednika). Preglednik je dugo koristio ugrađenu funkciju koja se naziva XMLHttpRequest za sve REST zahtjeve. Ali, ovo je naslijedio FetchAPI, moderan pristup zahtjevima zasnovan na obećanjima. Drugi primjeri su biblioteke koda poput axios, superagent i got ili neke namjenske aplikacije poput Poštara (ili mrežne verzije, poštarina!) Ili alat naredbenog retka poput CURL !.
  2. REST usluga : poslužitelj. Mnogo je popularnih knjižnica koje stvaraju ove poslužitelje, kao što su ExpressJS za NodeJS i Django za Python.
  3. REST API : ovo definira krajnju točku i metode kojima je dopušten pristup / slanje podataka poslužitelju. O tome ćemo vrlo detaljno govoriti u nastavku. Ostale alternative tome su: GraphQL, JSON-Pure i oData.

Pa recite mi sada, kako izgleda REST?

U vrlo širokim crtama, od poslužitelja tražite određene podatke ili tražite da spremi neke podatke, a poslužitelj odgovara na zahtjeve.

U programskom smislu, postoji krajnja točka (URL) koju poslužitelj čeka da dobije zahtjev. Povezujemo se s tom krajnjom točkom i šaljemo neke podatke o nama (sjetite se, REST je bez državljanstva, podaci o zahtjevu se ne pohranjuju), a poslužitelj odgovara ispravnim odgovorom.

Riječi su dosadne, dopustite mi da vam pokažem. Pomoću poštara pokazat ću vam zahtjev i odgovor:

Vraćeni podaci su u JSON-u (JavaScript Object Notation) i može im se pristupiti izravno.

Ovdje //official-joke-api.appspot.com/random_jokese naziva krajnja točka API-ja. Na toj će krajnjoj točki poslužiti poslužitelj za zahtjeve poput ovog koji smo postavili.

Anatomija ODMORA:

U redu, sada znamo da klijent može zatražiti podatke i poslužitelj će odgovoriti na odgovarajući način. Pogledajmo dublje kako se formira zahtjev.

  1. Krajnja točka : Već sam vam rekao o ovome. Za osvježavanje je to URL na kojem REST poslužitelj sluša.
  2. Metoda : Ranije sam napisao da možete tražiti podatke ili ih mijenjati, ali kako će poslužitelj znati kakvu operaciju klijent želi izvršiti? REST implementira više 'metoda' za različite vrste zahtjeva, a najpopularnije su sljedeće:

    - GET : Nabavite resurse s poslužitelja.

    - POST : Stvorite resurs na poslužitelju.

    - PATCH ili PUT : Ažurirajte postojeći resurs na poslužitelju.

    - DELETE : Izbrišite postojeći resurs s poslužitelja.

  3. Zaglavlja : Dodatni detalji predviđeni za komunikaciju između klijenta i poslužitelja (imajte na umu da je REST bez državljanstva). Neka od uobičajenih zaglavlja su:

    Zahtjev:

    - host : IP klijenta (ili odakle je zahtjev potekao)

    - jezik prihvaćanja : jezik koji klijent razumije

    - user-agent : podaci o klijentu, operativnom sustavu i dobavljaču

    Odgovor :

    - status : status zahtjeva ili HTTP koda.

    - vrsta sadržaja : vrsta resursa koju šalje poslužitelj.

    - set-cookie : postavlja kolačiće po poslužitelju

  4. Podaci : (naziva se i tijelom ili porukom) sadrži informacije koje želite poslati poslužitelju.

Dosta s detaljima - pokažite mi šifru.

Počnimo s kodiranjem usluge REST u Nodeu. Provest ćemo sve ono što smo gore naučili. Također ćemo koristiti ES6 + za pisanje naše usluge.

Provjerite imate li instaliran Node.JS nodei npmjesu li dostupni na vašoj putanji. Koristit ću čvor 12.16.2 i NPM 6.14.4.

Stvorite direktorij rest-service-nodei cd u njega:

mkdir rest-service-node cd rest-service-node

Inicijalizirajte projekt čvora:

npm init -y

-yZastava preskače sva pitanja. Ako želite ispuniti cijeli upitnik, samo pokrenite npm init.

Let's install some packages. We will be using the ExpressJS framework for developing the REST Server. Run the following command to install it:

npm install --save express body-parser

What's body-parser there for? Express, by default, is incapable of handling data sent via POST request as JSON. body-parser allows Express to overcome this.

Create a file called server.js and add the following code:

const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.json()); app.listen(5000, () => { console.log(`Server is running on port 5000.`); }); 

The first two lines are importing Express and body-parser.

Third line initializes the Express server and sets it to a variable called app.

The line, app.use(bodyParser.json()); initializes the body-parser plugin.

Finally, we are setting our server to listen on port 5000 for requests.

Getting data from the REST Server:

To get data from a server, we need a GET request. Add the following code before app.listen:

const sayHi = (req, res) => { res.send("Hi!"); }; app.get("/", sayHi);

We have created a function sayHi which takes two parameters req and res (I will explain later) and sends a 'Hi!' as response.

app.get() takes two parameters, the route path and function to call when the path is requested by the client. So, the last line translates to: Hey server, listen for requests on the '/' (think homepage) and call the sayHi function if a request is made.

app.get also gives us a request object containing all the data sent by the client and a response object which contains all the methods with which we can respond to the client. Though these are accessible as function parameters, the general naming convention suggests we name them res for response and req for request.

Enough chatter. Let's fire up the server! Run the following server:

node server.js

If everything is successful, you should see a message on console saying: Server is running on port 5000.

Note: You can change the port to whatever number you want.

Open up your browser and navigate to //localhost:5000/ and you should see something like this:

There you go! Your first GET request was successful!

Sending data to REST Server:

As we have discussed earlier, let's setup how we can implement a POST request into our server. We will be sending in two numbers and the server will return the sum of the numbers. Add this new method below the app.get :

app.post("/add", (req, res) => { const { a, b } = req.body; res.send(`The sum is: ${a + b}`); });

Here, we will be sending the data in JSON format, like this:

{ "a":5, "b":10 }

Let's get over the code:

On line 1, we are invoking the .post() method of ExpressJS, which allows the server to listen for POST requests. This function takes in the same parameters as the .get() method. The route that we are passing is /add, so one can access the endpoint as //your-ip-address:port/add or in our case localhost:5000/add. We are inlining our function instead of writing a function elsewhere.

On line 2, we have used a bit of ES6 syntax, namely, object destructuring. Whatever data we send via the request gets stored and is available in the body of the req object. So essentially, we could've replaced line 2 with something like:

const num1 = req.body.a; const num2 = req.body.b;

On line 3, we are using the send() function of the res object to send the result of the sum. Again, we are using template literals from ES6. Now to test it (using Postman):

So we have sent the data 5 and 10 as a and b using them as the body. Postman attaches this data to the request and sends it. When the server receives the request, it can parse the data from req.body , as we did in the code above. The result is shown below.

Alright, the final code:

const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.json()); const sayHi = (req, res) => { res.send("Hi!"); }; app.get("/", sayHi); app.post("/add", (req, res) => { const { a, b } = req.body; res.send(`The sum is: ${a + b}`); }); app.listen(5000, () => { console.log(`Server is running on port 5000.`); }); 

REST Client:

Okay, we have created a server, but how do we access it from our website or webapp? Here the REST client libraries will come in handy.

We will be building a webpage which will contain a form, where you can enter two numbers and we will display the result. Let's start.

First, let's change the server.js a bit:

const path = require("path"); const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.json()); app.get("/", (req, res) => { res.sendFile(path.join(__dirname, "index.html")); }); app.post("/add", (req, res) => { const { a, b } = req.body; res.send({ result: parseInt(a) + parseInt(b) }); }); app.listen(5000, () => { console.log(`Server is running on port 5000.`); }); 

We imported a new package path, which is provided by Node, to manipulate path cross-platform. Next we changed the GET request on '/' and use another function available in res, ie. sendFile, which allows us to send any type of file as response. So, whenever a person tries to navigate to '/', they will get our index.html page.

Finally, we changed our app.post function to return the sum as JSON and convert both a and b to integers.

Let's create an html page, I will call it index.html, with some basic styling:

     REST Client   * { margin: 0; padding: 0; box-sizing: border-box; } .container { height: 100vh; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; display: flex; flex-direction: column; justify-content: center; align-items: center; } form { display: flex; flex-direction: column; margin-bottom: 20px; } label, input[type="submit"] { margin-top: 20px; } 

Simple POST Form

Number 1: Number 2: Click Add!

Let's add a script tag just before the closing body tag, so we don't need to maintain a .js file. We will begin by listening for the submit event and call a function accordingly:

 document.addEventListener("submit", sendData); 

First we need to prevent page refresh when the 'Add' button is clicked. This can be done using the preventDefault() function. Then, we will get the value of the inputs at that instant:

function sendData(e) { e.preventDefault(); const a = document.querySelector("#num1").value; const b = document.querySelector("#num2").value; }

Now we will make the call to the server with both these values a and b. We will be using the Fetch API, built-in to every browser for this.

Fetch takes in two inputs, the URL endpoint and a JSON request object and returns a Promise. Explaining them here will be out-of-bounds here, so I'll leave that for you.

Continue inside the sendData() function:

fetch("/add", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify({ a: parseInt(a), b: parseInt(b) }) }) .then(res => res.json()) .then(data => { const { result } = data; document.querySelector( ".result" ).innerText = `The sum is: ${result}`; }) .catch(err => console.log(err));

First we are passing the relative URL of the endpoint as the first parameter to fetch. Next, we are passing an object which contains the method we want Fetch to use for the request, which is POST in this case.

We are also passing headers, which will provide information about the type of data we are sending (content-type) and the type of data we accept as response (accept).

Next we pass body. Remember we typed the data as JSON while using Postman? We're doing kind of a similar thing here. Since express deals with string as input and processes it according to content-type provided, we need to convert our JSON payload into string. We do that with JSON.stringify(). We're being a little extra cautious and parsing the input into integers, so it doesn't mess up our server (since we haven't implemented any data-type checking).

Finally, if the promise (returned by fetch) resolves, we will get that response and convert it into JSON. After that, we will get the result from the data key returned by the response. Then we are simply displaying the result on the screen.

At the end, if the promise is rejected, we will display the error message on the console.

Here's the final code for index.html:

     REST Client   * { margin: 0; padding: 0; box-sizing: border-box; } .container { height: 100vh; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; display: flex; flex-direction: column; justify-content: center; align-items: center; } form { display: flex; flex-direction: column; margin-bottom: 20px; } label, input[type="submit"] { margin-top: 20px; } 

Simple POST Form

Number 1: Number 2: Click Add! document.addEventListener("submit", sendData); function sendData(e) { e.preventDefault(); const a = document.querySelector("#num1").value; const b = document.querySelector("#num2").value; fetch("/add", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify({ a: parseInt(a), b: parseInt(b) }) }) .then(res => res.json()) .then(data => { const { result } = data; document.querySelector( ".result" ).innerText = `The sum is: ${result}`; }) .catch(err => console.log(err)); }

I have spun up a little app on glitch for you to test.

Conclusion:

So in this post, we learnt about REST architecture and the anatomy of REST requests. We worked our way through by creating a simple REST Server that serves GET and POST requests and built a simple webpage that uses a REST Client to display the sum of two numbers.

You can extend this for the remaining types of requests and even implement a full featured back-end CRUD app.

I hope you have learned something from this. If you have any questions, feel free to reach out to me over twitter! Happy Coding!