The foundations of REST APIs

Even though REST APIs do not have an official standard, most developers agree on the same foundation. It helps that HTTP, which is the protocol that this technology uses to communicate, does have a standard. In this section, we will try to describe how REST APIs should work.

HTTP request methods

We've already introduced the idea of HTTP methods in Chapter 2, Web Applications with PHP. We explained that an HTTP method is just the verb of the request, which defines what kind of action it is trying to perform. We've already defined this method when working with HTML forms: the form tag can get an optional attribute, method, which will make the form submit with that specific HTTP method.

You will not use forms when working with REST APIs, but you can still specify the method of the request. In fact, two requests can go to the same endpoint with the same parameters, headers, and so on, and yet have completely different behaviors due to their methods, which makes them a very important part of the request.

As we are giving so much importance to HTTP methods in order to identify what a request is trying to do, it is natural that we will need a handful of them. So far, we have introduced GET and POST, but there are actually eight different methods: GET, POST, PUT, DELETE, OPTIONS, HEAD, TRACE, and CONNECT. You will usually work with just four of them. Let's look at them in detail.

GET

When a request uses the GET method, it means that it is requesting for information about a given entity. The endpoint should contain information of what that entity is, like the ID of a book. GET can also be used to query for a list of objects, either all of them, filtered, or paginated.

GET requests can add extra information to the request when needed. For example, if we are try to retrieve all the books that contain the string "rings", or if we want the page number 2 of the full list of books. As you already know, this extra information is added to the query string as GET parameters, which is a list of key-value pairs concatenated by an ampersand (&). So, that means that the request for http://bookstore.com/books?year=2001&page3 is probably used for getting the second page of the list of books published during 2001.

REST APIs have extensive documentation on the available endpoints and parameters, so it should be easy for you to learn to query properly. Still, even though it will be documented, you should expect parameters with intuitive names, like the ones in the example.

POST and PUT

POST is the second type of HTTP method that you already know about. You used it in forms with the intention of "posting" data, that is, trying to update a resource on the server side. When you wanted to add or update a new book, you sent a POST request with the data of the book as the POST parameters.

POST parameters are sent in a format similar to the GET parameters, but instead of being part of the query string, they are included as part of the request's body. Forms in HTML are already doing that for you, but when you need to talk to a REST API, you should know how to do this by yourself. In the next section, we will show you how to perform POST using tools other than forms. Also note that you can add any data to the body of the request; it is quite common to send JSON in the body instead of POST parameters.

The PUT method is quite similar to the POST method. This too tries to add or update data on the server side, and for this purpose, it also adds extra information on the body of the request. Why should we have two different methods that do the same thing? There are actually two main differences between these methods:

  • PUT requests either create a resource or update it, but the affected resource is the one defined by the endpoint and nothing else. That means that if we want to update a book, the endpoint should state that the resource is a book, and specify it, for example, http://bookstore.com/books/8734. On the other hand, if you do not identify the resource to be created or updated in the endpoint, or you affect other resources at the same time, you should use POST requests.
  • Idempotent is a complicated word for a simple concept. An idempotent HTTP method is one that can be called many times, and the result will always be the same. For example, if you are trying to update the title of a book to "Don Quixote", it does not matter how many times you call it, the result will always be the same: the resource will have the title "Don Quixote". On the other hand, non-idempotent methods might return different results when executing the same request. An example could be an endpoint that increases the stock of some book. Each time you call it, you will increase the stock more and more, and thus, the result is not the same. PUT requests are idempotent, whereas POST requests are not.

Even with this explanation in mind, misusing POST and PUT is quite a common mistake among developers, especially when they lack enough experience in developing REST APIs. Since forms in HTML only send data with POST and not PUT, the first one is more popular. You might find REST APIs where all the endpoints that update data are POST, even though some of them should be PUT.

DELETE

The DELETE HTTP method is quite self-explanatory. It is used when you want to delete a resource on the server. As with PUT requests, DELETE endpoints should identify the specific resource to be deleted. An example would be when we want to remove one book from our database. We could send a DELETE request to an endpoint similar to http://bookstore.com/books/23942.

DELETE requests just delete resources, and they are already determined by the URL. Still, if you need to send extra information to the server, you could use the body of the request as you do with POST or PUT. In fact, you can always send information within the body of the request, including GET requests, but that does not mean it is a good practice to do so.

Status codes in responses

If HTTP methods are very important for requests, status codes are almost indispensable for responses. With just one number, the client will know what happened with the request. This is especially useful when you know that status codes are a standard, and they are extensively documented on the Internet.

We've already described the most important ones in Chapter 2, Web Applications with PHP, but let's list them again, adding a few more that are important for REST APIs. For the full list of status codes, you can visit https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.

2xx – success

All the status codes that start with 2 are used for responses where the request was processed successfully, regardless of whether it was a GET or POST. Some of the most commonly used ones in this category are as follows:

  • 200 OK: It is the generic "everything was OK" response. If you were asking for a resource, you will get it in the body of the response, and if you were updating a resource, this will mean that the new data has been successfully saved.
  • 201 created: It is the response used when resources are created successfully with POST or PUT.
  • 202 accepted: This response means that the request has been accepted, but it has not been processed yet. This might be useful when the client needs a straightforward response for a very heavy operation: the server sends the accepted response, and then starts processing it.

3xx – redirection

Even though you might think there is only one type of redirection, there are a few refinements:

  • 301 moved permanently: This means that the resource has been moved to a different URL, so from then on, you should try to access it through the URL provided in the body of the response.
  • 303 see other: This means that the request has been processed but, in order to see the response, you need to access the URL provided in the body of the response.

4xx – client error

This category has status codes describing what went wrong due to the client's request:

  • 400 bad request: This is a generic response to a malformed request, that is, there is a syntax error in the endpoint, or some of the expected parameters were not provided.
  • 401 unauthorized: This means the client has not been authenticated successfully yet, and the resource that it is trying to access needs this authentication.
  • 403 forbidden: This error message means that even though the client has been authenticated, it does not have enough permissions to access that resource.
  • 404 not found: The specific resource has not been found.
  • 405 method not allowed: This means that the endpoint exists, but it does not accept the HTTP method used on the request, for example, we were trying to use PUT, but the endpoint only accepts POST requests.

5xx – server error

There are up to 11 different errors on the server side, but we are only interested in one: the 500 internal server error. You could use this status code when something unexpected, like a database error, happens while processing the request.

REST API security

REST APIs are a powerful tool since they allow developers to retrieve and/or update data from the server. But with great power comes great responsibility, and when designing a REST API, you should think about making your data as secure as possible. Imagine— anyone could post tweets on your behalf with a simple HTTP request!

Similar to using web applications, there are two concepts here: authentication and authorization. Authenticating someone is identifying who he or she is, that is, linking his or her request to a user in the database. On the other hand, authorizing someone is to allow that specific user to perform certain actions. You could think of authentication as the login of the user, and authorization as giving permissions.

REST APIs need to manage these two concepts very carefully. Just because a developer has been authenticated does not mean he can access all the data on the server. Sometimes, users can access only their own data, whereas sometimes you would like to implement a roles system where each role has different access levels. It always depends on the type of application you are building.

Although authorization happens on the server side, that is, it's the server's database that will decide whether a given user can access a certain resource or not, authentications have to be triggered by the client. This means that the client has to know what authentication system the REST API is using in order to proceed with the authentication. Each REST API will implement its own authentication system, but there are some well known implementations.

Basic access authentication

Basic access authentication—BA for short—is, as its name suggests, basic. The client adds the information about the user in the headers of each request, that is, username and password. The problem is that this information is only encoded using BASE64 but not encrypted, making it extremely easy for an intruder to decode the header and obtain the password in plain text. If you ever have to use it, since, to be honest, it is a very easy way of implementing some sort of authentication, we would recommend you to use it with HTTPS.

In order to use this method, you need to concatenate the username and password like username:password, encode the resultant string using Base64, and add the authorization header as:

Authorization: Basic <encoded-string>

OAuth 2.0

If basic authentication was very simple, and insecure, OAuth 2.0 is the most secure system that REST APIs use in order to authenticate, and so was the previous OAuth 1.0. There are actually different versions of this standard, but all of them work on the same foundation:

  1. There are no usernames and passwords. Instead, the provider of the REST API assigns a pair of credentials—a token and the secret—to the developer.
  2. In order to authenticate, the developer needs to send a POST request to the "token" endpoint, which is different in each REST API but has the same concept. This request has to include the encoded developer credentials.
  3. The server replies to the previous request with a session token. This (and not the credentials mentioned in the first step) is to be included in each request that you make to the REST API. The session token expires for security reasons, so you will have to repeat the second step again when that happens.

Even though this standard is kind of recent (2012 onwards), several big companies like Google or Facebook have already implemented it for their REST APIs. It might look a bit overcomplicated, but you will soon get to use it, and even implement it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.228.138