randm's avatar
Level 6

How do I define an API route?

I never used Laravel to create API that return JSON. This time I have an application that need web routes and some API routes.

For my API route, I added the following route to my /routes/api.php file

Route::get('getinfo/{id}', 'InfoController@get')
    ->name('some_name')
    ->where('id', '[0-9]+');

However, when I go to /myapp.dev/api/getinfo/1 I get redirected to /home url.

What else that is different that I have to do to get the api routes to work?

0 likes
11 replies
Snapey's avatar

you would have to put your route in an api group to have an api prefix

Snapey's avatar

ok, sorry, I did not realise that.

Could you have a route in web.php that is being greedy and matching the API routes?

randm's avatar
Level 6

no because none of my routes in the web.php file start with prefix "api"

sutherland's avatar

Does the route use the auth:api middleware? It could be that if you are sending the request to an endpoint that requires authentication, it is looking for a token in the request headers. When it doesn't find the token, it throws an AuthenticationException. The exception handler catches this, and unless your request expects a JSON response via the appropriate headers, it redirects you to the login page. If you're logged in, the login page redirects you to /home.

This might be what's happening, I've seen the same happen to someone else on here. Try using a tool like Postman to test your API routes so you can specify the correct headers.

ThinkingMan's avatar

What version of Laravel? Are you running and returning error checks?

Snapey's avatar

no because none of my routes in the web.php file start with prefix "api"

i was checking you don't have a 'wildcard' route at the end of web.php

andreasbakir's avatar

Your wildcard {id}, what is it's corresponding model name? is it Id or does it have another name?

randm's avatar
Level 6

@Snapey I don't actually all of the available routes are grouped with a unique prefix.

@andreasbakir it corresponds to the model id.

randm's avatar
Level 6

@ThinkingMan I am using Laravel v5.5.13. I upgraded it from v5.4.

@sutherland I am not using that. As you can see the route is listed in my original question. but that is a good point

sutherland's avatar

@malhayek I figured you may have changed some details since some_name doesn't sound like a good route name. Well I would look for anything in your application that redirects to /home and try to reverse engineer where it could be originating. I know out of the box that the RedirectIfAuthenticated middleware does as well as the auth controllers. Try to figure out what's getting you there. Can you share your php artisan route:list?

Please or to participate in this conversation.