Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Laravel 7 REST API

101 views

Published on

Introduzione all'implementazione di REST API utilizzando il Framework PHP Laravel, un esempio CRUD di implementazione del servizio.

Published in: Software
  • DOWNLOAD THE BOOK INTO AVAILABLE FORMAT (New Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://urlzs.com/UABbn } ......................................................................................................................... Download Full EPUB Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download Full doc Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download PDF EBOOK here { https://urlzs.com/UABbn } ......................................................................................................................... Download EPUB Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download doc Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THE can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THE is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBOOK .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, CookBOOK, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, EBOOK, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THE Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THE the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THE Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Be the first to like this

Laravel 7 REST API

  1. 1. Laravel 7 Rest API
  2. 2. Corso Laravel di B. Ferrari2 Rest API REST significa Representational state transfer è un’architettura software che definisce le modalità in cui vengono creati servizi web. I servizi RESTful permettono a l’interoperabilità tra computer attraverso internet Questi servizi permetto di accedere ed elaborare risorse web, queste risorse sono identificate da una URL
  3. 3. Corso Laravel di B. Ferrari3 1 - Esempio REST API Students La rest API students è una CRUD API con i seguenti endpoints 1- GET /api/students restituisce tutti gli studenti. Questo endpoint accetta solo richieste GET 2- POST /api/students crea un nuovo studente. Questo endpoint accetta solo richieste POST 3- PUT /api/students/{id} aggiorna uno i dati di uno studente. Questo endpoint accetta solo richieste PUT 4- DELETE /api/students/{id} elimina uno studente. Questo endpoint accetta solo richieste DELETE
  4. 4. Corso Laravel di B. Ferrari4 2- Esempio REST API Students Requisiti Composer, Laravel 7, Postman e XAMPP I passaggi per la creazione della Rest API students sono i seguenti: 1- Avvio Servizi avvio Apache e MySQL da XAMPP Control Panel 2- Creazione Database creo database students usando phpmyadmin (accessibile all’indirizzo http://localhost/phpmyadmin) 3- Creazione progetto Laravel nella carella di root (c:/xampp/htdocs) creo il progetto students con il comando laravel new students 4- Creazione Model 4.1 Mi sposto nella cartella students comando cd students 4.2 Eseguo il comando php artisan make:model Student -m, che crea il model Strudent e migrazione
  5. 5. Corso Laravel di B. Ferrari5 3- Esempio REST API Students 5 – Configurazione Model in app/Student.php andiamo a configurare il model come segue. namespace App; use IlluminateDatabaseEloquentModel; class Student extends Model { protected $table = 'students'; protected $fillable = ['name', 'course']; }
  6. 6. Corso Laravel di B. Ferrari6 4- Esempio REST API Students 6 – Configurazione Migrazone nella cartella database/migrations troviamo la migrazione creata nel punto 4 . Apriamo la classe di migrazione e andiamo a implementare il metodo up come segue: ... public function up() { Schema::create('students', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('course'); $table->timestamps(); }); } …
  7. 7. Corso Laravel di B. Ferrari7 5- Esempio REST API Students 7 – Configurazione DB apriamo il file .env e andiamo a configurare il file come segue DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=<your-database-name> (students) DB_USERNAME=<your-database-username> (root) DB_PASSWORD=<your-database-password> 8- Migrazione eseguiamo la prima migrazione con il comando php artisan migrate questo andrà a creare la tabella come definito
  8. 8. Corso Laravel di B. Ferrari8 6- Esempio REST API Students 9 – Creazione Controller eseguiamo il comando php artisan make:controller StudentController che crea un controller vuoto in app/Http/Controllers/StudentController.php. Inseriamo i metodi CRUD come segue: class StudentController extends Controller { public function getAll() { // logic to get all students goes here } public function create(Request $request) { // logic to create a student record goes here } public function get($id) { // logic to get a student record goes here } public function update(Request $request, $id) { // logic to update a student record goes here } public function delete ($id) { // logic to delete a student record goes here } }
  9. 9. Corso Laravel di B. Ferrari9 7- Esempio REST API Students 10 Creazione Routes apriamo il file routes/api.php e inseriamo i punti di accesso della nostra api, aggiungendo il codice seguente: ... Route::get('student', 'StudentController@getAll'); Route::get('student/{id}', 'StudentController@get'); Route::post('student', 'StudentController@create'); Route::put('student/{id}', 'StudentController@update'); Route::delete('student/{id}','StudentController@delete'); … Nota: api.php tutte le route hanno prefisso /api per default
  10. 10. Corso Laravel di B. Ferrari10 8- Esempio REST API Students 11 Implementazione action: Implementiamo come segue la action create, il codice riceve in una POST i parametri name e post in formato x-www-form-url-encoded e crea un’instanza del classe student e tramite il suo metodo save viene memorizzato a database <?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppStudent; class StudentController extends Controller { ... public function create(Request $request) { $student = new Student; $student->name = $request->name; $student->course = $request->course; $student->save(); return response()->json([ "message" => "student record created" ], 201); } ... }
  11. 11. Corso Laravel di B. Ferrari11 9- Esempio REST API Students Possiamo verificare simulando una chiamata tramite Postman. Premiamo il pulsante NEW per creare una nuova chiamata di tipo POST e impostiamo com url http://localhost/students/public/api/student e andiamo a impostare i campi name e course da inserire in formato x- www-form-url-encoded
  12. 12. Corso Laravel di B. Ferrari12 10- Esempio REST API Students
  13. 13. Corso Laravel di B. Ferrari13 11- Esempio REST API Students Procediamo, in maniera analoga, con l’implementazione e test dei restanti metodi del controller public function getAll() { $students = Student::get()->toJson(); return response($students, 200); } public function get($id) { if (Student::where('id', $id)->exists()) { $student = Student::where('id', $id)->get()->toJson(); return response($student, 200); } else { return response()->json([ "message" => "Student not found" ], 404); } }
  14. 14. Corso Laravel di B. Ferrari14 12- Esempio REST API Students public function update(Request $request, $id) { if (Student::where('id', $id)->exists()) { $student = Student::find($id); $student->name = is_null($request->name) ? $student->name : $request->name; $student->course = is_null($request->course) ? $student->course : $request->course; $student->save(); return response()->json([ "message" => "records updated successfully" ], 200); } else { return response()->json([ "message" => "Student not found" ], 404); } }
  15. 15. Corso Laravel di B. Ferrari15 13- Esempio REST API Students public function delete ($id) { if(Student::where('id', $id)->exists()) { $student = Student::find($id); $student->delete(); return response()->json([ "message" => "records deleted" ], 202); } else { return response()->json([ "message" => "Student not found" ], 404); } }

×