Skip to content

REST Starter Guide

Apodemus Erectus edited this page Jun 10, 2020 · 16 revisions

In this guide I will explain REST APIs to the best of my ability. I recommend you first learn what REST APIs are and how to use them and only then dive into making them.

REST stands for "REpresentational State Transfer". It is a software architectural style that emphasises simplicity and uniformity. Relying on JSON responses to send out data. It is one of the most commonly used architectural styles for web APIs, although GraphQL is looking like it's going to be strong competitor to REST.

In simple terms:

  1. You: sends request
  2. Server: receives request
  3. Server: processes request
  4. Server: sends JSON response
  5. You: :)

Using a REST API

There is software for testing APIs without needing to write code, these are called REST clients. A few REST clients are: Postman and Insomnia. You can of course make requests in your code too.

The most important parts of a request are the method, the header and the body. You might be familiar with methods, they are basically HTTP methods: GET, POST, PUT, PATCH, DELETE, since REST uses the HTTP protocol. The headers specify some information about your request. The body is the data in your request.

JavaScript

Before using REST APIs in JavaScript, you should familiarise yourself with asynchrounous (async) programming concepts, because sending requests and fetching the response data in JavaScript is an async process. There are different ways to send a request en fetch the data in JavaScript.

XMLHttpRequest()

The XMLHttpRequest() is the original method of making requests, it has the widest browser support of all native JavaScript methods of making requests.

// Create a new XMLHttpRequest() object
let xhr = new XMLHttpRequest()

// When the response has been received, do this
xhr.onreadystatechange = function () {
    if (xhr.readyState === XMLHttpRequest.DONE) {
        // We're calling a REST API, so we need to parse the response text to JSON
        let JsonData= JSON.parse(xhr.responseText)
    }
}

// Specify the target URL and the method
xhr.open('POST', 'http://api.example.com', true)

// Set the header
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')

// Set the body
xhr.send('UwU nyaaaa! this is the data I want to send :3')

if you want to send JSON, you can use this. Make sure you place the right Content-Type in the header.

xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8")
xhr.send(JSON.stringify({ "email": "hello@user.com" }))

fetch()

Fetch() is similar to XMLHttpRequest(), but it works with promises.

fetch('http://api.example.com', {
    method: 'POST',
    body: JSON.stringify({
        "email": "hello@user.com"
    })
}).then(function(response) {
    return response.json()
}).then(function(data) {
    // Do a backflip or something else cool
})

Clone this wiki locally