Sei sulla pagina 1di 30

Advanced REST API in Laravel - Part 1

Azienda: NOVATEK SRL



Proponente: Danilo Costa

Titolo: CEO @ TeamNovatek, 

Software Application Developer

Dottore in Informatica


12/12/2017

URL: coderblock.com
Video Promo: bit.ly/coderblock-video-promo
About Me

About me

- CEO @ Team Novatek


- Web Application Developer
- 10 years on Web Development
- Background on CodeIgniter, Symfony, now Laravel full time
- About 4 years of experience building APIs
Topics

What’s the topics?

- Laravel MVC Application


- What’s an API REST?
- Simple way to structure an API
- Right Way to structure an API
- Strange examples of API applications (??)
Our application

Our Sample Application:


Simple CRM
- We’ll manage a database of agencies
- Each agencies has many customers
- Each agency has own User
- A User need to be able to Create/Read/Update/Delete (CRUD) a customer
- Application written with Laravel 5.3
Advanced API in Laravel

Structure of our Application

- Model (Eloquent ORM + database)


- Controller (routes + HTTP Controller)
- View (Blade view)
Advanced API in Laravel

Questions:

- What happens if we want to build a mobile application on the application data?


- What happens if we want to use a specific frontend? (AngularJS, React, ..)
- What happens if we want to let other companies work with our data?
Advanced API in Laravel

Solution:

Build an API REST!
(Application Programming Interface)

+
Webservices
Advanced API in Laravel

With Laravel, APIs building is very easy


(the easy way!)

- The client can access routes (just simple URLs)


- Controller accepts input and handle logic
- Controller returns data (for example, in JSON formats)

Advanced API in Laravel

With Laravel, APIs building is very easy


(the right way!)

- The client can access routes (just simple URLs)


- Controller accepts input and use specific modules to handle logic (Services,
Repositories)
- Services / Repositories handle logic (this time FOR REAL!)
- Service return data to Controller
- Controller formats data with Transformers

Advanced API in Laravel

API Routes: Naming


(the bad way!)

- /getAgencies
- /getUsers
- /removeCustomer
- /updateAgenciesInfo

Advanced API in Laravel

API Routes
(the REST way!)

CRUD Request

C - Create (POST)
R - Read (GET)
U - Update (PATCH/PUT)
D - Destroy (Delete)
Advanced API in Laravel

API Routes
(the REST way!)

POST /agencies - Create a new Agency


GET /users - Get All Users
PATCH /users/{id} - Update a User by ID
DELETE /customers/{id} - Destroy a customer by ID
Advanced API in Laravel

API Development: Magic Steps

1. Entity Migrations
2. Seed Data
3. Models
4. RESTful Routes
5. Controllers
6. Service/Repository Pattern
7. Format your output with Transformers!
Advanced API in Laravel

Entity Migration

Schema::create('users', function (Blueprint $table)


{

$table->increments('id');

$table->string('first_name')->nullable();

$table->string('last_name')->nullable();

$table->string('email')->unique();

$table->string('password');

$table->rememberToken();

$table->timestamps();

});
Advanced API in Laravel

Seed Data
$service = app(UserService::class);


// use the factory to create a Faker\Generator
instance

$faker = Faker::create();


foreach(range(1, env('users')) as $index) {


$user = User::create([

'first_name' => $faker->firstName,

'last_name' => $faker->lastName,

'email' => $faker->email,

'password' => bcrypt('member'),

]);


$service->create($user, 'member', 'member',
false);

}

Advanced API in Laravel

Controllers: Index & Show


GET All Users
 GET Single User

/users /users/{id}
/**
 /**

* Display a listing of users.
 * Display the specified user.

*
 *

* @return \Illuminate\Http\Response
 * @param int $id

*/
 * @return \Illuminate\Http\Response

public function index(Request $request)
 */

{
 public function show($id)

$users = $this->service->all();
 {

return response()->json($users);
 $user = $this->service->find($id);

} return response()->json($user);

}
Advanced API in Laravel

Controllers: Store & Update


POST Create User
 Update Single User

/users /users/{id}
/**
 /**

* Store a newly created resource in storage.
 * Update the specified resource in storage.

*
 *

* @param Request $request
 * @param Request $request

* @return \Illuminate\Http\Response
 * @param int $id

*/
 * @return \Illuminate\Http\Response

public function store(Request $request)
 */

{
 public function update(Request $request, $id)

$result = $this->service->create($request->except('_token'));
 {


 $result = $this->service->update($id, $request->except('_token'));

if ($result) {
 

return response()->json($result);
 if ($result) {

}
 return response()->json($result);


 }

return response()->json(['error' => 'Unable to create user'], 

500);
 return response()->json(['error' => 'Unable to update user'], 500);

} }
About Me

Controllers: Destroy
/**

* Remove the specified resource from storage.

*

* @param int $id

* @return \Illuminate\Http\Response

*/

public function destroy($id)

{

$result = $this->service->destroy($id);


if ($result) {

return response()->json(['success' => 'user was deleted'], 200);

}


return response()->json(['error' => 'Unable to delete user'], 500);

}
About Me

Pros and Cons - API v1


Pros:
- Easy to handle
- Separation of Concerns
Cons:
- No control on JSON outputs
- Can’t manage specific casting on data
- Can’t handle changes on data

Lavorare da Remoto: Significato

SOLUTION
Transformers for the WIN!

Which kind of package can be useful?


About Me

Nope, not the robots!


About Me

Transformers

Pros:
- Easy to handle
- Separation of Concerns

- Transform data by resource for API output
- Item and Collection
- Easy embed related resources
About Me

Transformers

Main RESTful API Packages:

- Fractal (part of League of Extraordinary Packages) http://fractal.thephpleague.com/


- Dingo (use Fractal internally) https://github.com/dingo/api
About Me

AgencyTransformer
/app/Transformer/AgencyTransformer.php

/**

* Turn this item object into a generic array

*

* @param Agency $item

* @return array

*/

public function transform(Agency $item)

{

return [

"id" => (integer) $item->id,

"name" => (string) $item->name,

"piva" => (string) $item->piva,

"maxPartecipants" => (integer) $item->max_partecipants,

"actualPartecipants" => (integer) $item->actual_partecipants,

"activation_fee" => (float) $item->activation_fee,

"monthly_fee" => (float) $item->monthly_fee,

"start_date" => (string) $item->start_date,

"end_date" => (string) $item->end_date,

"status" => (string) ($item->status != null) ? $item->status->label : null,

"user_id" => (string) ($item->users != null) ? $item->users->id : null

];

}
About Me

ApiController
It’s a best practices to use a Base ApiController to handle request response
class AgenciesController extends ApiController

class ApiController extends Controller



{

... ... ...


protected function respondWithItem($item, $callback)

{

$resource = new Item($item, $callback);


$rootScope = $this->fractal->createData($resource);


return $this->respondWithArray($rootScope->toArray());

}



protected function respondWithCollection($collection, $callback)

{

$resource = new Collection($collection, $callback);


$rootScope = $this->fractal->createData($resource);


return $this->respondWithArray($rootScope->toArray());

}
About Me

What about..?

- Testing
- Pagination with Cursor
- Validation
- Authentication
- Better error handling
- OOP + Design Patterns

See ya on part 2! ;)
Our Platform

)
Coderblock
;
n!
lia
Ita

Coderblock è un Recruitment Community Marketplace che si pone l’obiettivo di divenire punto di collegamento fra aziende
to

che necessitano di sviluppo tecnologico e professionisti altamente qualificati del settore.


h
itc
Sw

Dedicato alle aziende Dedicato ai Freelance


Mediante l’utilizzo delle ultime tecnologie, Un’ecosistema di freelance finalizzato alla
agevoliamo i processi produttivi aziendali,   crescita professionale, allo smart working,
ottimizzando la ricerca di personale alla condivisione e alla collaborazione in
qualificato. team.

Intelligenza Artificiale Remote Working


Grazie all’applicazione di algoritmi di Artificial UI e UX della piattaforma sono stati ideati
Intelligence, Coderblock consente all’azienda
  per agevolarne l’adozione e l’utilizzo e per
di creare, gestire e valutare team virtuali promuovere i concetti legati al lavoro
costruiti dinamicamente. Agile e da remoto.
La soluzione

MARKETPLACE WORKSPACE



PLATFORM

 
SOCIAL TEAM
Danilo Costa, CEO & Founder @ TeamNovatek

Grazie
per l’attenzione!

Potrebbero piacerti anche