I'm trying to create a very simple api, just to understand how to manage it.
I need to check if an "api key" is passed along side the url, my url should look like:
http://myapi.app/api/users?key=my-api-key
http://myapi.app/api/orders?key=my-api-key
So I have created a parent class to manage it in order to do not replicate all the login in every controller:
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Response as IlluminateResponse;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\App;
class ApiController extends Controller {
protected $isValid = true;
public function __construct()
{
$request = App::make('Illuminate\Http\Request');
if( ! $request->input('api_key') )
{
$this->isValid = false;
}
}
/**
* Per default lo status è 200 ovvero risposta corretta
*
* @var int
*/
protected $statusCode = 200;
/**
* @return mixed
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* @param mixed $statusCode
* @return $this
*/
public function setStatusCode( $statusCode )
{
$this->statusCode = $statusCode;
return $this;
}
/**
* @param string $message
* @return mixed
*/
public function respondNotFound( $message = 'Risorsa non trovata' )
{
return $this->setStatusCode( IlluminateResponse::HTTP_NOT_FOUND )->respondWithErrors( $message );
}
/**
* @param string $message
* @return mixed
*/
public function respondInternalError( $message = "Errore interno del server" )
{
return $this->setStatusCode( IlluminateResponse::HTTP_INTERNAL_SERVER_ERROR )->respondWithErrors( $message );
}
/**
* @param $data
* @param array $headers
* @return mixed
*/
public function respond( $data, $headers = [ ] )
{
return \Response::json( $data, $this->getStatusCode(), $headers );
}
/**
* @param $message
* @return mixed
*/
public function respondWithErrors( $message )
{
return $this->respond( [
'error' => [
'message' => $message,
'status_code' => $this->getStatusCode()
]
] );
}
}
And this is my TestController
<?php
namespace App\Http\Controllers\Api;
class TestController extends ApiController {
public function __construct()
{
parent::__construct();
if( ! $this->isValid )
{
return $this->respondWithErrors("no no");
}
}
public function test()
{
return "All ok";
}
}
The problem is that if I visit the url with Postman or via browser and I do not set the key
the test controller will always return All ok
, what am I missing?