REST Starter Guide - MiguelFieira/AMO-HANDBOEK GitHub Wiki

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": "[email protected]" }))

fetch()

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

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

jQuery ajax()

For all the filthy jQuery users out there:

$.ajax({
    type: 'POST',
    url: 'http://api.example.com',
    data: data,
})
.done(
    (data) => {
        console.log('I am a dirty jQuery user'+data)
    }
)

PHP

Sometimes you might want to make an API call on your server-side.

cURL

cURL is a computer software project providing a library (libcurl) and command-line tool (curl) for transferring data using various network protocols. The name stands for "Client URL", which was first released in 1997.

To be added...

Symfony request()

You can use the HttpClient component for making requests, you will need to call the request() method on HttpClient.

// This is how you can create a HttpClient
$client = HttpClient::create(['http_version' => '2.0']);

Then you can make a request like in the following example.

$response = $client->request('POST', 'http://api.example.com', [
    'headers' => [
        'Content-Type' => 'text/plain',
    ],
    'body' => [
        'email' => '[email protected]',
    ],
]);

The request() will return a response, which is asynchronous.

Making a REST API

For a guide on REST APIs in Symfony, see REST APIs.