Chapter 5.  Creating a RESTful Web Service

The goal of this chapter is to implement a RESTful Web Service that can be used to manage user profiles. Each user will have some basic contact information (such as a username, a given name, and a family name), a password for authentication, and a profile image.

This service will be implemented using the Slim micro framework, a small and lightweight framework that is available as an open-source library (MIT licensed) for PHP 5.5 and newer (we'll be using PHP 7, of course). For persistence, a MongoDB database will be used. This offers the perfect chance to explore PHP's MongoDB extension, which replaces the old (similarly named, but completely different) Mongo extension that was removed with PHP 7.

In this chapter, we will cover the following:

  • The basics of RESTful Web Services, most importantly the common HTTP request and response methods
  • Installing and using the Slim framework, and also the basics of the PSR-7 standard
  • Designing and implementing the actual example RESTful Web Service using the Slim framework and MongoDB storage
  • How to work with PSR-7 streams and store large files in a MongoDB database with GridFS

RESTful basics

In this section, we will recapitulate the basics of RESTful Web Services. You will learn about the basic architectural goals of REST Web Services and the most common protocol semantics of the Hypertext Transfer Protocol (HTTP), which is commonly used to implement such services.

REST architectures

The term Representational State Transfer was coined by Roy Fielding in 2000 and describes an architectural style for distributed systems that is, in principle, independent of any concrete communication protocol. In practice, most REST architectures are implemented using the Hypertext Transfer Protocol - in short, HTTP.

The key component of each RESTful Web Service is the resource. Each resource should meet the following requirements:

  • Addressability: Each resource must be identifiable by a Uniform Resource Identifier (URI), which is standardized in RFC 3986. For instance, a user with the username johndoe might have the URI http://example.com/api/users/johndoe.
  • Statelessness: The participants' communication between each other is stateless; this means that REST applications typically do not use user sessions. Instead, each request needs to contain all information that the server will need to fulfill the request.
  • Uniform interface: Each resource must be accessible by a set of standard methods. When using HTTP as a transfer protocol, you will typically use the HTTP methods for querying or modifying the state of resources. The next section of this chapter contains a short overview of the most common HTTP standard methods and response codes.
  • Decoupling of resources and representation: Each resource can have multiple representations. For example, a REST service might serve both a JSON and an XML representation of a user profile. Typically, the client specifies in which format the server should respond, and the server will choose a representation that best fits the requirements specified by the client. This process is called  Content Negotiation.

In this chapter, you will learn to implement all these architectural principles in a small RESTful Web Service. You will implement several different resource types with different representations and learn how to use different HTTP methods and response codes to query and modify these resources. Additionally, you will learn how you can use advanced HTTP features to your advantage (such as the rich set of cache-control headers).

Common HTTP methods and response codes

HTTP defines a set of standard methods (or verbs) that clients can use in requests, and status codes that servers can use in responses to said requests. In REST architectures, the different request methods are used to either query or modify the server-side state of the resource that is identified by the request URI. These request methods and response status codes are standardized in RFC 7231. Table 1 and Table 2 show an overview of the most common request methods and status codes.

The request methods GET, HEAD, and OPTIONS are defined as safe. Servers should not modify their own state when processing these kinds of requests. Furthermore, both the safe methods and PUT and DELETE methods are defined as idempotent. Idempotency means that repeated identical requests should have the same effect as a single request - for instance, multiple DELETE requests to the /api/users/12345 URI should still result in that one resource being deleted.

Table 1, Common HTTP request methods:

HTTP method

Description

GET

Used for querying the state of the resource identified by the URI. The server responds with a representation of the queried resource.

HEAD

Just like GET, except the server returns only the response headers and not the actual resource representation.

POST

POST requests can contain a resource representation in their request body. The server should store this object as a new sub-resource of the resource identified by the request URI.

PUT

Just like POST, PUT requests also contain a resource representation in their request body. The server should ensure that a resource with the given URI and representation exists and should create one if necessary.

DELETE

Deletes the resource with the specified URI.

OPTIONS

Can be used by clients to query which operations are allowed for a given resource.

Table 2: Common HTTP response status codes:

Status code

Description

200 OK

The request was successfully processed; the response message typically contains a representation of the requested resource.

201 Created

Like 200 OK, but in addition, explicitly states that a new resource was created by the request.

202 Accepted

The request was accepted for processing, but has not yet been processed. This is useful when a server processes time-consuming requests asynchronously.

400 Bad Request

The server was unable to interpret the client's request. This might be the case when a request contains invalid JSON or XML data.

401 Unauthorized

The client needs to authenticate before accessing this resource. The response can contain more information on the required authentication and the request can be repeated with appropriate credentials.

403 Forbidden

Can be used when the client was authenticated, but is not authorized to access a given resource.

404 Not Found

Used when the resource specified by the URI does not exist.

405 Method Not Allowed

The request method is not allowed for the specified resource.

500 Internal Server Error

An error occurred on the server while processing the request.

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

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