Create a simple, secure API
3
- Start with creating a folder in your plugins folder:
api
- Create
Plugin.php
with yourpluginDetails()
<?php namespace Aic\Api;
use System\Classes\PluginBase;
class Plugin extends PluginBase {
public function pluginDetails()
{
return [
'name' => 'API',
'description' => 'API for tracking application',
'author' => 'Meindert Stijfhals',
'icon' => 'icon-truck'
];
}
}
- Create
routes.php
<?php
Route::group(['prefix' => 'api/v1', 'middleware' => ['\Aic\Api\Http\Middleware\Auth']], function() {
Route::get('/orders', '\Aic\Api\Controllers\Orders@index');
Route::put('/orders/{id}', '\Aic\Api\Controllers\Orders@update');
});
- Create
http/middleware/Auth.php
<?php namespace Aic\Api\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class Auth
{
public function handle(Request $request, Closure $next)
{
$apiKey = $request->header('Authorization');
if ($apiKey !== env('API_KEY')) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $next($request);
}
}
- Create
controllers/Orders.php
<?php namespace Aic\Api\Controllers;
use Backend\Classes\Controller;
use Illuminate\Http\Request;
use Aic\Account\Models\Order;
class Orders extends Controller
{
public function index()
{
// do something...
// return Order::all();
return response()->json(['message' => 'API endpoint accessed successfully']);
}
public function update(Request $request, $id)
{
// $order = Order::findOrFail($id);
// do something...
// $order->update($request->all());
// return $order;
return response()->json(['message' => 'API endpoint accessed successfully']);
}
}
-
Add
API_KEY
with a good long secret value in your.env
file -
To test this, set up Postman and send 'Authorization' in header with your private key. Make sure your website is using HTTPS
There are no comments yet
Be the first one to comment