Chapter 4. Creating RESTful APIs

If there is one single core feature that demonstrates Laravel's superiority, it would be the ability to quickly and easily create a RESTful API. With the arrival of Laravel 5, several new features have been added; however, the ability to create application models and controllers via the Artisan command-line tool remains the most useful feature.

This feature is what initially encouraged me and so many others to abandon frameworks such as CodeIgniter, which at the time that Laravel 4 was in beta, did not natively have the same integrated functionality. Laravel provides the basic CRUD methods: create, read, update, delete, and also lists all.

Requests that arrive via HTTP to a Laravel URL are managed through their verbs and subsequently, the routes.php file, which is located at app/Http/routes.php. There are two ways in which the requests are handled. One way is that the request is handled directly via a closure, and the code is entirely inside the routes file. Another way is that it routes the request to a controller, where a method will be executed.

Also, the basic paradigm used is convention-over-configuration, where the method names are ready to handle the various requests, without too much extra effort.

RESTful APIs in Laravel

The list of RESTful API requests handled by the RESTful API are as follows:

 

HTTP VERB

Function

URL

1

GET

This lists all accommodations

/accommodations

2

GET

This shows (reads) a single accommodation

/accommodations/{id}

3

POST

This creates a new accommodation

/accommodations

4

PUT

This entirely modifies (updates) an accommodation

/accommodations/{id}

5

PATCH

This partially modifies (updates) an accommodation

/accommodations/{id}

6

DELETE

This deletes an accommodation

/accommodations/{id}

Most RESTful API best practices suggest using the plural form of the model name. Laravel's documentation uses the singular format. Most practices agree that consistent plural naming, that is, /accommodations/{id} refers to a single accommodation and /accommodations refers to more than one accommodation, both using the plural form are preferred over a mixed, but grammatically correct /accommodation/{id} (singular form) and /accommodations (plural form).

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

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