Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Repox's avatar
Level 4

Adding API routes to my Laravel application?

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\SurveyController@index');
    Route::post('/survey', 'Api\v1\SurveyController@newSurvey');
});

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);

    }
}
0 likes
3 replies
davorminchorov's avatar

What about a trait? Put the logic there and just use the trait in all of your controllers.

Repox's avatar
Level 4

That seems like a possible solution to verifying the API key at least. Do you have an idea to prettying up the response setup?

Please or to participate in this conversation.