# Learning Rest APIs
🔹 *parent* [[⧋ Becoming a RESTful API Developer]]
▫️ *related* [[⧋ JavaScript]], [[⏶ APIs|API]], *next* [[✦ Designing RESTful APIs|Designing RESTful APIs]]
## Overview
**REST API:** Representational State Transfer Application Programming Interface
Allow for the separation of the *presentation of content* from the *content itself*.
## Quick Commands
GET
```bash
GET https://regres.in/api/users // add ?options=value
Host: appsite.dev
Authorization: Basic [name] [pass]
Content-Type: application/json
Cache-Control: no-cache
OPTIONS http://restful.dev/w-ison/w/v2/posts/
Authorization: Basic [name/pass]
HEAD https://regres.in/api/users
```
POST
```bash
POST /wp-json/v2/posts HTTP/1.1
Host: appsite.dev
Authorization: Basic Morten pass
Content-Type: application/json
Cache-Control: no-cache
{
"title": "A post created via the REST API!",
"content": "This is the content of the post created with the REST API.",
"status": "publish",
"author": 1
}
```
PUT / PATCH / DELETE
```bash
PUT http://restful.dev/wp-ison/wp/v2/posts
Authorization: Basic morten b
Content-Type: application/json
{
"title": "The new REST API title",
}
# DELETE - adds to trash but not permanent delete
DELETE http://restful.dev/wp-ison/wp/v2/posts/15
# OPTIONS can find info how how to permanently delete, for instance
DELETE http://restful.dev/wp-ison/wp/v2/posts/15?force=true
```
## Rest API explained
### The RESTful librarian
The Rest API is much like a librarian that acts as an intermediary between the service making a request for data and the database of information.
The client submits a request for a resource,
- it identifies the data and what format,
- it creates a representation of the data matching the requested format,
- bundles the data with metadata like resource ID, and hyperlinks to available actions, media formats related to this response, and time of response
- sends it back to the client
- the client then parses the data to make it meaningful on its end
The client will then send changes to the REST API service
- using a PUT request using the original ID
- the REST service notes the media format requested
- Identifies the requested resource
- Converts the requested data into a media format that works for the data store
- Makes the changes submitted
- Returns the new representation of the resource along with a success message to notify the client everything went as expected
### What is a REST API?
Accoding to [[#^5b7152|MDN]]:
> *"Representational State Transfer (REST) refers to a group of software architecture design constraints that bring about efficient, reliable, and scalable systems."*
Rest isn't a specific technology a but rather a data architecture methodology that produces a predictable set of outputs by receiving a set of standard methods (called *verbs*) and returning standardized structured data (JSON, XML) called a *resource*.
While it's possible to make a request for a resource, returning HTML, CSS, JS, and JSON data for each request, it's better to receive the provided structure for that data initially and then only update the data itself while leaving the structure unchanged.
For instance LinkedIn is going to pull the same data but form it differently based upon the specific format of web application or mobile app. Once established it will govern the flow of information using **GET, PULLS, PUT, and DELETE**,
Anki: What are the 4 standard methods for regulating flow of information of a resource?
GET, PULL, PUT, and DELETE
### Sidebar: URI vs URL
What is the difference between URL and URI?
**URI (Universal Resource Identifier)** - "A compact sequence of characters that identifies an abstract or physical resource" that "provides a simple and extensible means for identifying a resource"
**URL (Universal Resource Locator)** - Subset of URI that identifies a resource and explains how to access that resource by providing an explicit method like https:// or ftp://
All URLs are URIs, but not all URIs are URLs
Anki: What do URI and URL stand for? What is the difference?
URI is general compact sequence of characters that identifies a resource, while URL is a subset that identifies how to access a specific resource.
### The six constraints of REST
1. Client-server architecture
2. Statelessness
3. Cacheability
4. Layered system
5. Code on demand
6. Uniform interface
**Client-server architecture** - The client manages user interface concerns while the server manages data storage concerns.
**Statelessness** - No client context or information, aka "state", can be stored on the server between requests. (i.e. authentication tokens)
**Cacheability** - All REST responses must be clearly marked as cacheable or not cacheable.
**Layered System** - The client cannot know, and shouldn't care, whether it's connected directly to the server or to an intermediary like a CD or mirror.
**Code on demand** - Servers are allowed to transfer executable code like JavaScript and compiled components to clients.
**Uniform interface**:
- 6.1 Resource identification in request - requiring what format a request needs to be returned in.
- 6.2 Resource manipulation through representations - once a resource has been received, ability to modify the *representation* of that resource.
- 6.3 Self-descriptive messages - each respresentation must describe it's data format so that it can be reliably parsed.
- 6.4 Hypermedia as the engine of application state - once access to a resource is given to a REST service, all resources and methods available should be provided.
Once these constraints have been met, a resource can be considered a RESTful API.
### How REST relates to HTTP
Not all REST resources use HTTP protocol (they're not intrinsicly linked) but the *RESTful resources* do use HTTP.
REST can also run on FTP or SMTP or some other protocol.
The web platform is what makes a REST service *RESTful*.
Anki:
What makes a service RESTful?
Only a REST service utilizing a web platform accessed through HTTP is RESTful.
### Who or what interacts with REST APIs?
What does it mean when it's said that a *"client is consuming the REST API?"*
Humans are *operators* of clients, but the clients are the *website or app itself*.
While an operator might create an API and clients are allowed to consume the data provided by that API, the operator can define *limits* or rules to how that API will be consumed. For example common rules for social media resources:
- username/password requirement to know who accessed data
- rate limits ("API limit reached")
### Tools to see REST API in action
API test service
[Reqres - A hosted REST-API test service](https://reqres.in)
- fake data
- real responses
- always on
You can use the REQUEST info provided in a URL to return RESPONSE data.
Clients
- Postman
- Insomnia
- VS Code - **REST Client** extension

In VS Code
- Create new project folder
- Add a **rest.http** file within that folder (or call it whatever you want)
- Add GET request in correct format
```api
GET https://regres.in/api/users
```
- Typing this will make 'Send Request' appear above command. If you click it will return resource information (header, data, structured data).
## Request
### Anatomy of REST request
Useful information in a GET request might include Host, Content-Type, Authorization, Cache-Control, and more.

In a POST type, the data structure of the request needs to match the content type defined in the request.
```api
POST /wp-json/v2/posts HTTP/1.1
Host: appsite.dev
Authorization: Basic Morten pass
Content-Type: application/json
Cache-Control: no-cache
{
"title": "Angela creates a new task generated
from the REST API"
"content": "This is the content for the new
post."
"author": 10,
}
```
In vanilla JavaScript this would look something like this
- open the get request
- capture the response to be logged in the console
```js
var hr = new XMLHttpRequest();
xhr.open ("GET", " https://site.com/wp-json/w/v2/posts", true);
xhr.onload = function () {
console.log (xhr.responseText);
};
xhr.send();
```
jQuery request would look like this
```js
$.ajax({
url: " https://site.com/wp-json/wp/v2/posts",
type: "POST",
data: {
title: "Angela creates a new task generated from the REST API",
content: "This is the content for the new post.",
author: 10, },
success: function(response) {
console.log (response);
}
});
```
### Discovery
A good API has documentation. But the API will also describe itself with its own response methods.
By running `OPTIONS` on a post resource, I can return all information related to POST for that resource and its methods:

A developer will use discovery along with experimentation in order to figure out how to use a resource.
### Resource
>*"The key abstraction of information in REST is a resource. Any information that can be named can be a resource: a document or image, a temporal service, a collection of other resources, a non-virtual object and so on.
>
>In other words, any concept that might be the target of an author's hypertext reference must fit within the definition of a resource.
>
>A resource is a **conceptual mapping** to a set of entities, not the entity that corresponds to the mapping at any particular point in time."*
>- Roy Fielding
**Singletons** can be accessed through increased specificity in the URL route, with the first part poiting toward a *resource collection* while the last element refers to a specific *resource singleton* within that collection:

Bookcase - the entire bookcase
Books - all books within the bookcase
Red - all red books in the bookcase
cubby - Red books within the cubby of the bookcase
Unlike a library where you checkout the actual book, instead you checkout a *representation* of that resource, allowing multiple clients to access this resource in different formats.
Resource vs Representation
### Methods
GET - get what exists at this address and return it to me
- Success (200) or
- Failure (404) not found
POST - create a new resource and add it to collection
- Success (201) or
- Failure (401 unauthorized, 409 conflict, 404 not found)
PUT - update data with new information provided
- Success (200)
- Failure (401, 404, 405 method not allowed)
PATCH - modify a resource without replacing everything
- Success (200)
- Failure (401, 404, 405 method not allowed)
DELETE
- Success (200)
- Failure (401, 404)
OPTIONS - returns options for that resource
HEAD - returns head of response
## Response
### Response Header
`HEAD` is used by the client to view the return data.
- success failure
- date/time, server type, data type, content-type (format)
Status message is most important part

### HTTP Status Messages
Response codes are broken into the following sections:
- 1xx Information - rare. Status of server.
- 2XX Success - Common. Successful request or add.
- 3XX Redirection - Client is provided with new URL for resource (redirection, permanent move, temporary, resume incomplete)
- 4xx Client error - bad request, unauthorized, forbidden, not found, method not allowed.
- 5xx Server error - internal server, bad gateway, service unavailable
### REST and Authorization/Authentication
Most REST resources have levels of authorization for types of request
For instance
- Any user can make GET
- Authorized users can retrieve more methods (via header authentication)
- Each method can also have differing levels of access
## Request/Response pairs
### Request/Response pairs
First discover with OPTIONS request
```api
OPTIONS http://restful.dev/w-ison/w/v2/posts/
Authorization: Basic [name/pass]
```
Use the response to find arguments needed to get specific response resources

### GET
Now I can use GET method to view the response data and discover more about the results.
```api
GET http://restful.dev/w-ison/w/v2/posts/
Authorization: Basic [name/pass]
```
Returns full resource of all posts

I can then string the options I found earlier to the GET request to return a specific supset of data to return:
```api
GET http://restful.dev/w-ison/w/v2/posts?per_page=1
Authorization: Basic [name/pass]
```
Now I'm only going to get a single item, or however many I specify.
If I go to the end of the returned post data, I can find a direct link to this specific post and the collection it resides within. This URL can be added to the GET request to return the exact post.

### POST
POST can be used to create new resources.
Must use the correct format:
- URI
- Authorization
- Type
- JSON with title, content, status, author
```api
POST http://restful.dev/wp-ison/wp/v2/posts
Authorization: Basic morten b
Content-Type: application/json
{
"title": "A post created via the REST API!",
"content": "This is the content of the post created with the REST API.",
"status": "publish",
"author": 1
}
```
Anytime you make a post, it will return the entire resource created by that POST
The returned DATA is useful and can be used
- Location (URI)
- Add Location URI to a GET requestion to return all useful info
### PUT/PATCH
What if I want to edit part of an existing POST, rather than completely changing or deleting? PUT/PATCH will allow me to access and change certain properties of post.
POST, PUT, PATCH will do different things depending on the resource.
Send an `OPTIONS` request to find out `args` for the API's methods
With PUT I can change only the portion I want to change
```api
PUT http://restful.dev/wp-ison/wp/v2/posts
Authorization: Basic morten b
Content-Type: application/json
{
"title": "The new REST API title",
}
```
### DELETE
By using DELETE, it won't actually delete the post, but will change the post's status to "trash", which is the same as what it would do via wordpress by clicking "trash" on the individual post.

It adds it to the 'Trash' list (no longer public)

In order to fully delete, I'd need to check `OPTIONS` to return information on how to permanently delete a resource.

This reveals that in order to delete a post, I need to add the argument `force=true` at the end of my DELETE request for the individual post.
```api
DELETE http://restful.dev/wp-ison/wp/v2/posts/15?force=true
```
Now attempting to `GET` that specific resource will return a 404 error
## References
1. REST - MDN Web Docs Glossary: Definitions of Web-related terms [MDN](https://developer.mozilla.org/en-US/docs/Glossary/REST) ^5b7152