Introduction to REST API

TIL 2021.02.23

Day 75: Treehouse Full Stack JavaScript Techdegree

REST is a common method for one computer to communicate with another.

A REST API

  • is basically a server-side web application that receives and transmits information from and to a browser or another computer.
  • Doesn’t send out webpages, instead it sends out and receives information and processes that input to store data and perform tasks like completing an online order or returning the results of a search.

API (Application Programming Interface)

  • One of the most commonly used interfaces for sharing information across both internal products and third party data sources such as twitter or google.
  • To provide a programmatic interface

REST (Representational State Transfer)

  • Another layer on top of HTTP, the hypertext transfer protocol — which is the foundation for all communication on the internet.

The web, by design is stateless, this means that every request that you make to a website is like meeting that site for the first time — it is not storing any information. After each request, the server forgets your client entirely.

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

ENDPOINTS

Resource

  • A model in our application
  • For example, we are holding on to players scores in our game — the player and the scores are resource
  • These resources are what we want to retrieve, create and modify through our API
  • We do the CRUD operations at specific URLs — which are called ENDPOINTS

Endpoints

  • Represents a single record or a collection of multiple records
  • Typically the resource name needs to be plural because the default action is to get a collection

VERBS — HTTP METHODS

In RESTful API design they are actions you take on the resources

Instead of being on the URL , they’re represented by the type of request the client makes to the API

There are four main verbs or HTTP methods we use for Rest Apis

GET

  • Fetching either a collection of resources or a single resource

POST

  • Add a new resource to a collection. For example, we would not POST to games/123 or players/12345 because they aren’t collections. But we can use POST on /players or /games because they are a collection of resources — to create a new player or new game

PUT

  • HTTP method or Verb that we use when we want to update a record. We would not use PUT on a collection or list URLs.

DELETE

  • Sending a DELETE request to a detail record, a URL for a single record, should just delete that record.
  • Sending DELETE to an entire collection would delete the whole collection — not usually implemented

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

REQUESTS

Using postman:

Add JSON

And we can send more information to the API through parameters

These are known as a query or query string

And now by having the query string value as javascript, the API will return all the information that relates to javascript and my profile. Look at the badges.

Everything after the ? is treated as a set and key value pairs

/api/v1/games?order=desc&sort=points

In this example, the keys are order and sort while the values are desc and points

In our HTTP example, users request the format by adding a .json to the URL

We could also send this information using the HTTP headers

By placing the key as Accept and the value as application/json

And it would still return the data in JSON format

HTTP headers are useful

The HTTP spec provides a very useful list of headers that can and should be accepted by the API

HTTP Headers

  • Accept: Specifies the file format the requester wants
  • Accept-Language: Specifies the human readable language like English or Spanish
  • Cache-Control: Specifies whether the response can be generated from a cache a quick to access memory bank of data or not

People take advantage of HTTP headers to make transactions cleaner and more explicit

Most get endpoints accept their parameters through the query string where they are URL encoded. Post requests encode their content as either xwww form URLencoded or form data and typically send it through as the body of the request — which hides the data from the URL but still makes it available to the API

GET — on the URL as query string parameters

POST — on the body of the request

In our examples earlier /api/v1/users/567

The v1 specifies the version of the API that we’re hitting — we always want to provide version numbers for our apis and we want to make sure that the legacy APIs exists for as long as possible

When your app comes out with a brand new version and we need a new API for it, bump the version number up and keep the old API around for as long as you can

The longer our APIs version sticks around, the less web breaks

When consuming a third party API, make sure you reference documentation for the particular version you are using as versions can vary greatly

Also a good idea to upgrade to the latest API versions when possible — not only to get the latest features but to also make sure that your application continues to work as expected

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

RESPONSES

Like an HTTP Request, an HTTP Response also has headers

The Content-Type header is used to specify what type of response is returned — this should match the type that was requested

When we remove the .json on the URL or Accept application/json on the header, the default Content-Type is HTML

In the response headers, there are a lot of headers like Status. Status are the status code that tells us a lot about the state of the bit of content and we can use them in an API to communicate the state of the request

Status codes are broken up into four chunks — each 100 numbers apart

200–299: Content is good and everything is okay/action has been taken and no error has happened — for example if a user sends a POST then we will return a 201 which indicates that the POST was successful

300–399: the request was understood but the requested resource is now located elsewhere — used to perform redirects to new URLs

400–499: errors typically generated by the client, the request was wrongly constructed 400 or a resource that no longer exists 404, or the request that is allowed is GET and no one can USE POST, PUT or DELETE which returns a 405

500–599: Errors on the server’s end

Useful headers, correct status codes, appropriate format and useful data all combine to make a great HTTP response for an API

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

SECURITY

The first step in making sure that your API is available for clients is usually caching

1. Cache

  • A service that runs in memory to hold recently requested results — like a newly created record or a large data set
  • Helps to prevent database calls and even costly calculations on your data

Maybe your data is spread across several databases and gathering up all that information, sorting it and presenting it to the user may take several seconds

Putting that final calculated data into a cache means that subsequent lookups only take as long as required for your cache to find and return the right key

2. Rate Limiting

  • Each user is allowed a certain number of requests to your API in a given time period
  • Once a user exhausts their allotment, they would have to wait until the timer runs out so that they can get more
  • Helps prevent users from flooding us with requests
  • Prevents DDOS(distributed denial of service) attacks

3. Authentication

  • What if we need to restrict certain information to certain users — we need some way to verify that a user is who they say they are
  • Different APIs handles authentication differently

A few ways authentication requests can be handled

  • API Tokens
  • When setting up an API account a user is given a token and a secret pair
  • The user will pass those credentials when making a request to the server which allows the API server to verify the communication
  • The server takes the pair credentials and checks that they’re active proper users in the database
  • Users need to include their token with every request because of the statelessness of HTTP — authentication happens with each request
  • Most of the time the token and secret are included as keys in the JSON or XML data that a client will send but it is possible to be included in the authentication headers in the HTTP request

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store