HTTP & REST 101
Tags: http, rest, api, webdev
Published: 2022-12-01 16:49:03

## What is HTTP?

HTTP stands for Hyper Text Transfer Protocol and is what defines how the communication should be between web servers and clients. It follows a _client-server_ model where clients open a connection to make a request and waits until it receives a response from a server. 

Every request in HTTP is independent of another, this means that servers do not keep any data between requests and is why HTTP is considered to be a _stateless_ protocol.

The main parts of HTTP are: _header fields_, _request methods_ and _status codes_.

## Header fields
Headers are pieces of information that are included in every request and response. These fields are values and are used to indicate a specific piece of information regarding the request or response and consists of a case-insensitive name followed by a colon and then by its value.
These can be classified into 3 categories with some examples of the most common headers:
- **General**:
   - _Request URL_: The URL used in the request.
   - _Request Method_: Which HTTP method was used.
   - _Status Code_: Code indicating the result of the request.
- **Response**
   - _Server_: Type of server used.
   - _Set-Cookie_: Used to set a cookie from server to client .
   - _Content-Type_: The type of the responses data.
- **Request**
   - _Cookies_: Extra information attached to the request.
   - _Content-Type_: The type of data sent.
   - _Authorization_: A token used for validating a user.

Below is a real example of the headers present in a GET request to obtain a website’s html body:

![Request example showing headers used](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p5rhbds65bo03j4kl4iz.png)




## Request Methods
Every HTTP request uses an HTTP method used to identify a different type of operation to be done. The most commonly used methods are:
- **GET**: Retrieve data from the server. For example, getting data about all products in a store.
- **POST**: Submit data to the server. For example, creating a new user.
- **PUT**: Update data already on the server. For example, updating a user’s address.
- **DELETE**: Delete data from the server. For example, deleting an item from a catalog.

There are also other less common methods such as _PATCH_, _OPTION_, _HEAD_, _CONNECT_ and _TRACE_.


## Status Codes
Status codes are used in responses to indicate the result of a request by a server. For example a client sends a GET request to a server, and then the server returns a response to the client with a property called status code which tells the client what happened to its request such as if it was successful or if an error occurred. There are many status codes which can be grouped into ranges which tell generally what happened with the request:

- **_100-199_ Informational responses**: Tells information about the request such as if it was received or is processing.
- **_200-299_ Successful responses**: Successfully received, understood and accepted.
- **_300-399_ Redirection messages**: Redirect user, further action must be taken.
- **_400-499_ Client error responses**: Request does not have what it needs.
- **_500-599_ Server error responses**: Server failed to fulfill an apparent valid request.

Each status code number is used to specify a specific scenario, but with this information we can tell by the range the number belongs to what happened to the request in a general manner.  For example if it belongs to the _2xx_ range we can tell that the status is ok, if its _4xx_ we know something went wrong client side with the request and it its _5xx_ we can determine that an error occurred in the server’s side. If we wanted to examine further, we can consult what the specific code means in a HTTP status codes reference guide.

## Endpoints
A REST API is accessed with an endpoint URL such as: `http://myWebsite/posts?id=123`.
In this example of an endpoint, `http://` is the _protocol_, `myWebsite` is the _domain name_ and `/posts` is the _resource_, which is how the user tells the API what type of information it's trying to interact with. Lastly, `?id=123` are the _query parameters_, which in this case contains the `id` variable with a value of 123.

## What is REST?
_REST_ is a standardized software architecture style for API’s that stands for _Representational State Transfer_. This style contains standard design principles that focus on the communication between services to communicate in a simple and standardized way. 

The the main characteristics of _REST API’s_ are that they are **scalable**, **stateless** and **high performant**. 

It is scalable because when a service grows in complexity it's easy to make modifications. 

It is stateless because requests are independent and you don't need to keep track of the data between requests. 

REST API’s have high performance mostly because they support _caching_, which means that whenever several requests for the same information are received, caching allows to cache the API response in order for following requests to be faster and avoid having to process them again.

In order to follow REST design principles in an API there are **6 constraints** that should be followed:
1. **Uniform Interface**: 
   - Resources must have uniform resources, using the URL to identify a resource.
   - Manipulation must be done through representations (information in a data format such as JSON).
   - Messages are self-descriptive.
   - HATEOAS is used when server responds with data about what the client can do next through hyperlinks.
2. **Client-Server**:
   - Clients and servers must be decoupled, meaning that they should be able to operate or evolve independently as long as the interface is not altered.
3. **Stateless**:
   - The necessary state to handle the request is contained within the request itself in part of the URI, query parameters, body or headers.
4. **Cacheable**:
   - Server responses must indicate whether they can be cached or not. This is done to improve performance and reduce server load.
5. **Layered System**:
   - A client cant tell wether its connected to the end server or an intermediary server.
6. **Executable Code (optional)**:
   - Servers can extend or customize the functionality of a client by transferring executable code, for example in HTML script tags. 

## How REST and HTTP are related
Sometimes there is confusion between the two terms and are used interchangeably, however they represent different things. REST is a set of best practices of an architectural style while HTTP is a defined protocol with rules for communication. In other words, REST defines how HTTP should be used.

## Conventions for good API design
Some additional conventions that are considered to be good practices that should be considered while designing an API are:
1. **Resources**:
   - Resources should be named according to collections and instances, and these names should be nouns, not verbs. For example `/song/123` instead of `/getSong`.
2. **Behavior**:
   - HTTP methods do not have a 1:1 relationship with CRUD (Create Read Update Delete). For example for submitting data to a server (C in CRUD), POST or PUT methods could be implemented, not just POST.
3. **Documentation**:
   - Documentation should be easy to find, show clear examples of complete request/response cycles and should keep users updated of changes.
4. **Versioning**:
   - Ensure backwards compatibility using versioning whenever breaking changes to the API are made. Versioning can be done through specifying the API version in the URL or headers. 
5. **Other**
   - Other good conventions to follow are: result filtering and ordering, allow users to limit fields returned by API, pagination, rate limiting and error handling.

	

---


## References:
- Grace Hopper Academy. (2017). REST Tutorial - How to Design a Good RESTful API [Video]. Retrieved December 1, 2022, from: https://www.youtube.com/watch?v=sMKsmZbpyjE
- IBM Technology. (2020). What is a REST API? [Video] Retrieved December 1, 2022, from: https://www.youtube.com/watch?v=lsMQRaeKNDk
- MDN. (2022). HTTP. _MDN_. Retrieved December 1, 2022, from:  https://developer.mozilla.org/en-US/docs/Web/HTTP
- Rest API Tutorial. (2012). What is REST? _Rest API Tutorial_. Retrieved December 1, 2022, from: https://www.restapitutorial.com/lessons/whatisrest.html#
- Traversy Media. (2019). HTTP Crash Course & Exploration [Video]. Retrieved December 1, 2022, from: https://www.youtube.com/watch?v=iYM2zFP3Zn0