Sunday, April 9, 2023

[phpsandbox][laravel][web] quick setup laravel API service

 .

0) Create a phpsandbox account

Surf to https://phpsandbox.io

Create an account e.g. using Google account. 


(1) Create PHP Laravel Project

Select Laravel version e.g. Laravel 8

Type a name e.g. lara8api


(2) Configure Database

In config/database.php edit as follows:

    |--------------------------------------------------------------------------

    | Default Database Connection Name

    |--------------------------------------------------------------------------

        'default' => env('DB_CONNECTION', 'sqlite'),

    |--------------------------------------------------------------------------

    | Database Connections

    |--------------------------------------------------------------------------

        'sqlite' => [

            'driver' => 'sqlite',

            'url' => env('DATABASE_URL'),

            'database' => database_path('database.sqlite'),

            'prefix' => '',

            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),

        ],


(3) Edit api script file

(In route/api.php)


<?php


use Illuminate\Http\Request;

use Illuminate\Support\Facades\Route;

use Illuminate\Support\Facades\DB;

use Illuminate\Database\Schema\Blueprint;


/*

|--------------------------------------------------------------------------

| API Routes

|--------------------------------------------------------------------------

|

| Here is where you can register API routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| is assigned the "api" middleware group. Enjoy building your API!

|

*/




Route::get('/hello', function () {

    return( 'hello');

});


Route::get('/init', function () {

    Schema::dropIfExists('student');

    if (!Schema::hasTable('student')) {

        Schema::create('student', function (Blueprint $table) {

            $table->id();

            $table->string('name');

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

        });

    }

    

    $json_data = '{"table":"student","status":"init"}';


    $result = json_decode($json_data);


    return response()->json($result, 201);

});


Route::match(array('GET', 'POST'),'/getall', function () {

    $student = DB::select('select * from student');

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

});

Route::get('/insert/{name}/{email}',function($name,$email){

    $timestamp = time();

    DB::insert('insert into student (id, name,email) 

        values (?, ?,?)', 

        [$timestamp,$name.'_'.$timestamp,$email.'_'.$timestamp]);

    echo "record inserted.<br/>";

});


Route::post('/insert',function(Request $request)

  {

    $payload = json_decode($request->getContent(), true);

    try {

      // Get data here, eg. make an external API request or DB query

      $response = [

        'name' => $payload['name'],

        'email' => $payload['email']

      ];


    $timestamp = time();

    DB::insert('insert into student (id, name,email) 

        values (?, ?,?)', 

        [$timestamp,$response['name'].'_'.$timestamp

        ,$response['email'].'_'.$timestamp]);



    } catch (\GuzzleHttp\Exception\BadResponseException $e) {

      $errorResJson = $e

        ->getResponse()

        ->getBody()

        ->getContents();

      $errorRes = json_decode(stripslashes($errorResJson), true);

      // Return error

      return response()->json(

        [

          'message' => 'error',

          'data' => '$errorRes'

        ],

        $errorRes['response']['code']

      );

    }

    // Return success

    return response()->json(

      [

        'status' => '200',

        'data' => '$response',

        'message' => 'success'

      ],

      200

    );

  }

);


Route::post('/update',function(Request $request)

  {

   $payload = json_decode($request->getContent(), true);

    try {

      $response = [

        'id' => $payload['id'],

        'name' => $payload['name'],

        'email' => $payload['email']

      ];


    $affected = DB::update(

    'update student set name = ?, email=? where id = ?',

    [$response['name'],$response['email'],$response['id']]);



    } catch (\GuzzleHttp\Exception\BadResponseException $e) {

      $errorResJson = $e

        ->getResponse()

        ->getBody()

        ->getContents();

      $errorRes = json_decode(stripslashes($errorResJson), true);

      // Return error

      return response()->json(

        [

          'message' => 'error',

          'data' => '$errorRes'

        ],

        $errorRes['response']['code']

      );

    }

    // Return success

    return response()->json(

      [

        'status' => '200',

        'data' => $affected ,

        'message' => 'success'

      ],

      200

    );

  }

);



Route::post('/delete',function(Request $request)

  {

   $payload = json_decode($request->getContent(), true);

    try {

      $response = [

        'id' => $payload['id']

      ];


    $deleted = DB::delete('delete from student where id = ?', 

    [$response['id']]);



    } catch (\GuzzleHttp\Exception\BadResponseException $e) {

      $errorResJson = $e

        ->getResponse()

        ->getBody()

        ->getContents();

      $errorRes = json_decode(stripslashes($errorResJson), true);

      // Return error

      return response()->json(

        [

          'message' => 'error',

          'data' => '$errorRes'

        ],

        $errorRes['response']['code']

      );

    }

    // Return success

    return response()->json(

      [

        'status' => '200',

        'data' => $deleted ,

        'message' => 'success'

      ],

      200

    );

  }

);


.

No comments:

Post a Comment