yusufcodes / restapi-laravel

A REST API built using Laravel

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool



Laravel REST API - Study Notes

Introduction

These are some study notes I’ve taken as part of the PluralSight course: RESTful Web Services with PHP and Laravel in conjunction with the Laravel Documentation

Credit to the author, Maximilian Schwarzmüller, for helping me learn this Laravel knowledge and come up with these study notes.

If you want to try this course out for free, check out PluralSight’s Free Trial to give the course a go!

Module 1: Designing and Structuring a RESTful Service

This module was more theoretical, focusing on decomposing an API idea and listing out the different endpoints that you may require.

Main HTTP Methods

  • GET: Retrieve a resource
  • POST: Add a resource
  • PUT: Replace a resource
  • PATCH: Update parts of a resource
  • DELETE: Remove a resource

API Endpoint Examples

Below is an example of the different API endpoints on the project worked on in the course.

GET
Get List of all Meetings
Get Data about Individual Meetings

POST
Create Meeting
Register for Meeting
Create User
User Signin

PUT
Update Meeting

Module 2: Routing

Creating a Route

Below is an example of a POST route, accessible via the ‘/post’ path. This example triggers the create method in the PostController controller. The name of this route is set to post.create. If needed, middleware can be specified, and in this example, the auth middleware is set.

Route::post('/post', [
	'uses' => 'PostController@create',
	'as' => 'post.create',
	'middleware' => 'auth'
]);

Creating RESTful Routes

Above shows the way to create a traditional route, however with a RESTful API, we may need many different routes to handle different actions.
Although these can be configured manually, Laravel offers a way to generate multiple routes easily.

The resource() method will create multiple routes for us, which are linked to different controller actions in the specified controller.

Route::resource('post', 'PostController');

These are the following routes which are created with the resource method:

| HTTP Method & URL  | Controller Action |
| ------------- | ------------- |
| GET /post  | index [show all posts]  |
| GET /post/create  | create [get creation form]  |
| POST /post  | store [store post on server]  |
| GET /post/{post}  | show [get single post] |
| GET /post/{post}/edit  | edit [get edit form]  |
| PUT/PATCH /post/{post}  | update [save update on server]  |
| DELETE /post/{post}  | destroy [delete post on server] |

Creating RESTful Controllers

The different RESTful routes which were created in the previous section link to various controller actions. To set up the controller along with the RESTful controller actions, use the following command:

php artisan make:controller PostController --resource

The command creates a controller as normal, but the –resource flag populates the controller with the methods that are expected by the RESTful route created earlier.

Route Grouping

Often you may have multiple routes which you want to have the same prefix. For example, let’s take the following prefix: api/v1.
If we want all of our routes to contain this prefix, the following method will help us achieve this without repeating ourself upon the creation of each of these routes:

// State the prefix you want for the contained routes
Route::group(['prefix' => 'api/v1'], function() {
	// Place any routes in here
	Route::post('/post', [...]);
});

Module 3: Request Handling and Responses

Sending Requests and Getting a Response

The general path for a request in Laravel is as follows:

Client -> Router -> Middleware -> Controller

  • Client: The user making the request to our application.
  • Router: The Laravel Router which will appropriately handle the request, by pointing it towards the correct controller.
  • Middleware: Requirements that must be fulfilled before reaching the controller. This can prevent unauthorised users from accessing certain parts of an application, for example, an area of the website which requires you to be logged in.
  • Controller: The endpoint of a request, where the desired action is performed on the request and returned.

Accessing Input

Inputs can be retrieved from the Request object (Illuminate\Http\Request).
For example, from some JSON data, an input with the name ‘title’ can be accessed via the following:

$title = $request->input('title');

Responses

Common responses from a controller can include a HTML pages, JSON, a file, or plain text.

Returning a response

Amongst all of the different responses that can be sent back to the user, JSON is very common.
Laravel has a built-in JSON method which will convert a PHP associative array into the respective JSON format. This is achieved using the built in json_encode PHP function.

return response()->json($associativeArray, 200);

General things to include in a response:

  • Message: Success or failure of the request made by the user, with a description of what is being achieved. This is so the user knows exactly what has happened with their request.
  • Data: Any data associated with the request being made. For example, if a user has created a new post, you could include the title of it to confirm the new post has been created.
  • Link: A link to the resource which is related to the request that is made. This is so the user can access their newly created resource.

Validation

Laravel has a built-in validator, which can validate any data that comes through a request.
The validate method is used, which specifies the different rules that should be followed for the different inputs from a given request.
Parameters:

  1. Request: The request which the data needs to be validated for
  2. Associative Array: an associative array specifying the validation rules
$this->validate($request, [
	'title' => 'required|max:120',
	'content' => 'required'
]);

Module 4: CRUD Operations

Creating Models and Migrations

Models: Classes which are used to interact with a corresponding database.

For example, a ‘Post’ model could be used to interact with a ‘posts’ database table.

Migrations: Files which handle the creation and configuration of database tables.

Artisan Commands for Models and Migrations

Query 1: Creating a model, with a corresponding migration file (-m).
Query 2: Creates a migration file separate to any model creation.

Query 1: php artisan make:model Post -m
Query 2: php artisan make:migration PostTableMigration

Configuring a Database Table

Configurations for a database table are held in the up() method.
In here, you can define the various fields you would like your table to have. Example:

$table->dateTime('time');
$table->string('title');
$table->text('description');

Once you have configured your migration files to reflect the database table you want to create, run the following command, which will create the tables in the database:

php artisan migrate

Defining Relations

Once your models have been created, stored in the App folder, you can set up relations between them.

Example: Let’s take the relationship between a Post and a Comment.
A Post could have many comments. To define this relationship in Laravel, you define the following function in the Post model:

public function comments()
{
	// Passing in the name of the related model into the hasMany method
	return $this->hasMany('App\Comment');
}

On the other side of the relationship, a Comment can only belong to one particular post. To define this relationship in Laravel, you define the following function in the Comment model:

public function post()
{
	return $this->belongsTo('App\Post');
}

Interacting With Data - One to Many

Below is an example of finding a Post, and adding a Comment to it.

// Retrieving the post you want, by ID
$post = Post::find(1);

// Initialising a new Comment model, with the related data $comment = new Comment(data);

// Calling the comments() method on the Post model, to store the comment in relation to the post that has been retrieved. // Laravel auto-generates the post_id foreign key entry in the database for this comment. $post->comments()->save($comments);

Interacting With Data - Many to Many

The process is similar between models which have a many to many relationship, but instead you use the attach method. Attach ensures that the foreign key entry is not only created in the related model’s table, but also in the pivot table. Below is an example:

$post = Post::find(1);
$user = new User(data);
$post->users()->attach($user);

Interacting with Data - Eloquent Methods

As I completed the implementation of this section of the course, many different methods were used when interacting with data in relation to the databases. Below, I’ve tried to summarise some of the important ones that were used:

// The notes refer to a 'Model', which can be any model you may be working with in Laravel. 

// Storing a model in the database /* The method will return true upon success, which can be used to determine the actions to take when a record has been inserted. */ $model->save()

// Retrieving all of the models from the database $models = Model::all();

// Let model = meeting, relatedModels = users /* A meeting can have one or more users, and a user can be registered for one or more meetings. The attach metod adds the entry for this many to many relationship in the pivot table. */ $model->relatedModels()->attach($id);

// Get all of the data for the specified model, as well as the defined relatedModel defined $model = Model::with('relatedModel');

// Retrieves the first result of a query, or will otherwise throw an exception. A 404 HTTP response is automatically generated and sent back to the user. $model = Model::findOrFail($id);

// Removes the entry in the pivot table between models which have a many to many relationship. $model->relatedModels()->detach();

Module 5: Authentication

Introduction

Authentication with a RESTful service is a bit different to the usual application that you may build.

RESTful Services are Stateless, meaning you cannot store a session. This is a general characteristic of REST.

A solution is to have a token which the server can authenticate as being valid. This isn’t stored on the server, but the processing of such tokens will occur on the server.

Note: Due to having some setup issues with JWT following the tutorial, I decided not to carry on working on the module.
If possible, I plan to come back to the module to take the time to work through the issues I was facing.

About

A REST API built using Laravel


Languages

Language:PHP 97.4%Language:HTML 2.6%