Tuesday 18 June 2024

Create Routes for a Laravel 11 API Model

Laravel routes are used to bind URLs to controller actions. REST methods are often used to describe the type of HTTP action which the route will respond to. 

Pre-requisites

Check to see if you already have a routes/api.php for this model.
This should have been created by running:
php artisan install:api

Now create a route for our class:
Route::apiResource('/yourmodelname', YourController::class);
Now in the terminal:
php artisan route:list --path=api
This creates a list of all the endpoints. You may wish to make a copy of these.

Before we can test the endpoints, we should add a response in our controller. I like to add
return response()->json(['message' => 'Hello World!']);
to the public function index().

We should now be in a position to test our endpoints.
We should run the server as:
php artisan serve
Then use a tool like Postman to test the first endpoint.
Commonly, when working locally, this would take the form of a GET request to and endpoint of:
http://localhost:8000/api/yourcontrollername
We should now see some JSON showing the message "Hello world".

No comments:

Post a Comment