#Accessing api route from api.php

16 messages · Page 1 of 1 (latest)

warm whale
#

Hi, a long time ago I created an api route. Route::post('/checkCustomUrl', [App\Http\Controllers\ApiController::class, 'getCustomUrl']); this should be accessible for example in postman placing /api/checkCustomUrl am I right? Cause now apparently the call returns the html of the homepage. Although the url seems correct, I added the necessary body and header to access the route. And ofcourse put the request on POST in postman

warm whale
#

Nevermind forgot the header Accept: application/json

radiant kiln
#

I usually add a middleware to api routes that add the accept json header if it's missing. People often forget it.

warm whale
#

might be interesting cause sometimes I forget that too

#

I believe as simple as this php public function handle(Request $request, Closure $next) { $request->headers->set('Accept', 'application/json'); return $next($request); } i've also seen another example where they just send a message, please provide json header, but this seems better, otherwise people need to keep manually add that header in case they forget

radiant kiln
#

Yeah that's it.

warm whale
#

I stored my custom header token btw in the .env file, is that safe?

radiant kiln
#

Yeah that's were secret stuff is meant to be.

warm whale
#

alright, some people say make a config file, but even the db details are stored in there

#

same as my postmark stuff etc

radiant kiln
#

Both are true. The value should be stored in .env, but in the code you should fetch the value via config(). This is because the env() function doesn't work in production where the config is cached.

warm whale
#

@radiant kiln ah i can see in config/mail.php that i use env varaibles where i have stored the shared hosting it's own smtp details

#

I can see that I have my own custom env variable here ```php
public function createUser(Request $request){
abort_if($request->header('X-API-TOKEN') !== env("X_API_TOKEN"), 401, 'Unauthorized');

radiant kiln
#

Yeah but that in a config file. You could add a new config/api.php:

<?php

return [
    'token' => env('X_API_TOKEN'),
];

And then in the app you access it with config('api.token')