Repox
549
3
Laravel

Adding API routes to my Laravel application?

Posted 3 years ago by Repox

So, basically I'm pretty far with my small web application and now I want to add a few simple API endpoints that returns some JSON responses.

I think my current solution is bad because I feel I'm forcing JSON responses (especially when validating requests) and my way of checking for the API key (and validating it) it centralized into the controller (and is forcing me to do it again in other controllers). I should probably move the API key check into some middleware, but then I have to somehow make the $application variable accessible to the controllers.

Anyway, I'd appreciate some input on my solution - the following is how my small and simple API is set up now.

Route

Route::group(['prefix' => 'api/v1', 'middleware' => ['api']], function() {
    Route::get('/', 'Api\v1\[email protected]');
    Route::post('/survey', 'Api\v1\[email protected]');
});

SurveyController

<?php

namespace App\Http\Controllers\Api\v1;

use App\Apikey;
use App\Jobs\SendRequestEmail;
use App\Score;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use Illuminate\Support\Facades\Validator;

class SurveyController extends Controller
{
    private $application;

    public function __construct(Request $request)
    {
        if (!$apikey = $request->header('X-api-key', false)) {

            if (!$apikey = $request->get('api_key', false)) {
                abort(401, 'API key is not provided', ['Content-Type' => 'application/json']);
            }
        }

        if (!$apikey = Apikey::where('key', $apikey)->where('active', true)->first()) {
            abort(403, 'API key cannot be found or is no longer active', ['Content-Type' => 'application/json']);
        }

        $this->application = $apikey->application;
    }

    public function index(Request $request)
    {
        return response()->json(['status' => 'ok']);
    }

    public function newSurvey(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'name' => 'string',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        $score = new Score($request->all());

        $this->application->scores()->save($score);

        $job = (new SendRequestEmail($this->application, $score));
        $this->dispatch($job);

        return response(null, 201);

    }
}

Please sign in or create an account to participate in this conversation.