REST APIs with JSON
Learn how modern applications serving APIs communicate with the world and their relationship with JavaScript.
For many years, the primary goal of the PHP application was to generate HTML pages. Now it’s changing.
- First, single-page applications are becoming more common. In these applications, the server sends a single HTML file containing only a link to a JavaScript bundle that builds the whole document on the client-side.
- Second, monoliths are getting replaced with collections of microservices. Most PHP services are never meant to be called directly by the browser but instead, by other services.
In both cases, PHP applications need to provide a convenient API for other programs. And, that’s why the REST API is popular.
What is the REST API?
Representational state transfer (REST) is an architectural style for distributed hypermedia systems proposed by Roy Thomas Fielding. It doesn’t instruct how to implement such systems but instead applies some constraints to their elements.
- It has to be a client-server architecture in which the client and server can evolve independently.
- Client-server requests have to be stateless. The server cannot store session data. The client is responsible for keeping the session’s context.
- The server has to be able to label some responses as cacheable.
- There has to be a uniform interface between all the components in the system.
- The client can’t indicate whether the server that it sends the request to is the end server that can handle it. It can be a layered system in which each component can only see the next layer.
- The last (optional) constraint is a code-on-demand style. It allows the client to extend the functionality by downloading code from the server as applets and scripts.
The unit of information in a REST API is a resource. A resource can be any information we can name and give a unique identifier.
Clients usually don’t see resources in the same form that the server uses to store them. Instead, clients see resource representations ...