ctrlaltdelme's avatar

Building a REST API and endpoints?

I've read around a lot and looked at the Laravel Docs and have wanted to build a REST API for an app for a while, but haven't been exactly clear on how to go about it.

It seems Sanctum would be used, but am not sure. How would I go about adding a restful API that users can access using something like Postman to get data back?

0 likes
3 replies
JussiMannisto's avatar

Using Sanctum:

  1. Define an API route.
  2. Add the auth:sanctum middleware on that route. You can use the ability middleware for additional authorization checks, if needed.

You can issue API tokens for users using $user->createToken(). The token needs to be included in API requests as a Bearer token. That means API requests should have a header like this:

Authorization: Bearer your-plain-text-token-here

P.S. APIs are meant for machine-to-machine communication, not direct end user interaction. Tools like Postman are intended for development and debugging.

jlrdw's avatar

First, will the API also be used for a mobile app, in which case you have to do a front end.

If not, you just give detailed instructions on how to use the API. The user, company, or whatever handles their own front end in their code base.

Here is just an example of instructions I used in the past for a Humane Society.

https://partner-apis.adoptapet.com/

But the chapter in the laravel docs has this how to for laravel called:

Eloquent: API Resources

https://laravel.com/docs/12.x/eloquent-resources#main-content

Edit:

An end user of the API should be allowed to use a variety of technologies. Some users for example may be using .Net core, some Java, etc.

So if the API is for anyone, then you need the applicable instructions.

But of course you could have it only for PHP, i.e., Laravel, Cakephp, etc.

And some may use Axios js, some Fetch js, some curl, etc.

Just some things to keep in mind.

I have seen so many post here of folks that are doing an API, but in most of those cases a regular web app that's mobile friendly would have been better suited.

martinbean's avatar

@ctrlaltdelme You define API-specific routes that call API-specific controllers to return API-specific responses:

API routes: https://laravel.com/docs/routing#api-routes

Then create controllers that return say, Eloquent API resources as responses:

class ArticleController extends Controller
{
    public function index()
    {
        $articles = Article::query()->latest()->paginate();

        // Show a list of articles, with automatic pagination metadata...
        return ArticleResource::collections($articles);
    }

    public function show(Article $article)
    {
        // Show a single article...
        return ArticleResource::make($article);
    }
}

If you use Eloquent resources, then your responses will be a consistent “shape” no matter if you’re showing a single record or many.

Please or to participate in this conversation.