CodeBlanks Logo Icon CodeBlanks

REST API basics

PHP course · Advanced · Lesson 52/92

Learn the basics of REST architecture and the resource concept.

REST and the resource concept

REST is a style for designing resource-based APIs over HTTP. A resource is a unit of data on the server: a user, a task, a product. Each resource is addressed by a URL; for example, /users/42 refers to the user with id 42.

The client accesses the resource with HTTP methods: read, create, update, or delete. The server returns the response in a structured data format that the client parses and uses.

The stateless principle

In REST, each request must stand on its own. The server does not keep client state between requests; this is the stateless principle. Every request carries all the information it needs within itself.

This principle simplifies the server and makes scaling easier. Any server handling the request gives the same answer, because state lives in the resource, not the session. Session data is sent as parameters or headers inside the request.

Exercise Return a resource representation as a string

Write a function called getResource. It should take a parameter $id. Inside, build an array with keys id, title and done (title value 'Task', done value false). Encode this array with encode and UNESCAPED_UNICODE, and return it. Then print the result of getResource(7).

Show example solution
Define getResource, put an encode call inside with return, then call it with echo.
Example solution:
function getResource($id) {
    $resource = ['id' => $id, 'title' => 'Task', 'done' => false];
    return encode($resource, UNESCAPED_UNICODE);
}
echo getResource(7);

Test yourself

  1. A data unit addressed by a URL

    In REST, a data unit addressed by a URL is called a ____; for example, /tasks/7 is a task resource.
    Show answer
    In REST, a data unit addressed by a URL is called a resource; for example, /tasks/7 is a task resource.
  2. Match the REST concepts

    resource
    data addressed by URL
    HTTP method
    operation on a resource
    URL
    address of the resource
    response
    server's return value
  3. What does the stateless principle mean?

    • The server re-requests all session data on every request
    • Each request is complete on its own; the server keeps no state between requests
    • The client only talks to a single server
    • Requests only use the GET method
    Show answer

    Each request is complete on its own; the server keeps no state between requests — Correct. In the stateless principle, each request is complete on its own and the server keeps no state between requests.

All lessons in Advanced