Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

Create a simple, secure API

3
by AIC BV, last modified on February 20th, 2024
  1. Start with creating a folder in your plugins folder: api
  2. Create Plugin.php with your pluginDetails()
<?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'
        ];
    }

}
  1. 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');
});
  1. Createhttp/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);
    }
}
  1. 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']);
    }
}
  1. Add API_KEY with a good long secret value in your .env file

  2. To test this, set up Postman and send 'Authorization' in header with your private key. Make sure your website is using HTTPS

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?