30
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 Advanced REST API in Laravel - Part 1

Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

  • Upload
    vankien

  • View
    256

  • Download
    4

Embed Size (px)

Citation preview

Page 1: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

Azienda: NOVATEK SRLProponente: Danilo Costa Titolo: CEO @ TeamNovatek, Software Application Developer

Dottore in Informatica12/12/2017

URL: coderblock.com

Video Promo: bit.ly/coderblock-video-promo

Advanced REST API in Laravel - Part 1

Page 2: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

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

Page 3: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

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 (??)

Page 4: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

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

Page 5: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

Advanced API in Laravel

Structure of our Application

-Model (Eloquent ORM + database) - Controller (routes + HTTP Controller) - View (Blade view)

Page 6: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

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?

Page 7: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

Advanced API in Laravel

Solution:Build an API REST!

+Webservices

(Application Programming Interface)

Page 8: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

Advanced API in Laravel

With Laravel, APIs building is very easy

- The client can access routes (just simple URLs) - Controller accepts input and handle logic - Controller returns data (for example, in JSON formats)

(the easy way!)

Page 9: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

Advanced API in Laravel

With Laravel, APIs building is very easy

- 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

(the right way!)

Page 10: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

Advanced API in Laravel

API Routes: Naming

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

(the bad way!)

Page 11: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

Advanced API in Laravel

API Routes

CRUD Request

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

(the REST way!)

Page 12: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

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

Page 13: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

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!

Page 14: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

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();});

Page 15: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

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);}

Page 16: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

Advanced API in Laravel

Controllers: Index & Show

/** * Display a listing of users. * * @return \Illuminate\Http\Response */public function index(Request $request) { $users = $this->service->all(); return response()->json($users);}

/** * Display the specified user. * * @param int $id * @return \Illuminate\Http\Response */public function show($id) { $user = $this->service->find($id); return response()->json($user);}

GET All Users/users

GET Single User/users/{id}

Page 17: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

Advanced API in Laravel

Controllers: Store & Update

/** * Store a newly created resource in storage. * * @param Request $request * @return \Illuminate\Http\Response */public function store(Request $request) { $result = $this->service->create($request->except('_token')); if ($result) { return response()->json($result); } return response()->json(['error' => 'Unable to create user'], 500); }

/** * Update the specified resource in storage. * * @param Request $request * @param int $id * @return \Illuminate\Http\Response */public function update(Request $request, $id) { $result = $this->service->update($id, $request->except('_token')); if ($result) { return response()->json($result); } return response()->json(['error' => 'Unable to update user'], 500); }

POST Create User /users

Update Single User/users/{id}

Page 18: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

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);}

Page 19: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

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

Page 20: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

Lavorare da Remoto: Significato

SOLUTION

Which kind of package can be useful?

Transformers for the WIN!

Page 21: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

About Me

Nope, not the robots!

Page 22: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

About Me

Transformers

Pros: - Easy to handle - Separation of Concerns - Transform data by resource for API output - Item and Collection - Easy embed related resources

Page 23: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

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

Page 24: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

About Me

AgencyTransformer

/** * 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 ]; }

/app/Transformer/AgencyTransformer.php

Page 25: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

About Me

ApiController

class AgenciesController extends ApiController

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

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());}

Page 26: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

About Me

What about..?

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

See ya on part 2! ;)

Page 27: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application
Page 28: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

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

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

Un’ecosistema di freelance finalizzato alla crescita professionale, allo smart working, alla condivisione e alla collaborazione in team.

Dedicato ai Freelance

UI e UX della piattaforma sono stati ideati per agevolarne l’adozione e l’utilizzo e per promuovere i concetti legati al lavoro Agile e da remoto.

Remote Working

Mediante l’utilizzo delle ultime tecnologie, agevoliamo i processi produttivi aziendali,

ottimizzando la ricerca di personale qualificato.

Dedicato alle aziende

Grazie all’applicazione di algoritmi di Artificial Intelligence, Coderblock consente all’azienda

di creare, gestire e valutare team virtuali costruiti dinamicamente.

Intelligenza Artificiale

Our Platform

Switch to

Italia

n! ;)

Page 29: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

La soluzione

PLATFORM

MARKETPLACE

SOCIAL

WORKSPACE

TEAM

Page 30: Advanced REST API in Laravel - Part 1 - GrUSPpalermo.grusp.org/.../2017/01/2017_0111_Advanced-API-in-Laravel.pdf · Advanced REST API in Laravel - Part 1. About Me About me ... -Application

per l’attenzione!Grazie

Danilo Costa, CEO & Founder @ TeamNovatek