How to create Laravel API

Create a Laravel API using an example: step-by-step guide to building a robust, secure RESTful API.

Creating a Laravel API

In order to create an API in Laravel, there are a few steps that need to be taken. First, a route must be created to handle the request. A route is the entry point for the API, and it defines what type of request can be made, and how it should be handled. Then, a controller must be created, which is responsible for handling the request and returning a response. Finally, the response must be formatted. This can be done using the JSON format.

Defining the Route

The first step in creating an API is to define the route. In Laravel, this is done using the Route:: method. The following code creates a route that can handle both GET and POST requests. It also defines a name for the route, which can be used to refer to it later:

Route::post('/api/users', 'UserController@store')->name('user.store');
Route::get('/api/users/{id}', 'UserController@show')->name('user.show');

The first line creates a route for a POST request to the /api/users URL. It also specifies that this request should be handled by the UserController@store method. The second line creates a route for a GET request to the same URL, but with an id parameter. This request should be handled by the UserController@show method.

Creating the Controller

The next step is to create a controller to handle the request. This controller is responsible for retrieving the data from the database and formatting it into a response. The following is an example of a controller that handles the UserController@store route:

public function store(Request $request)
{
    $user = User::create($request->all());
 
    return response()->json([
        'data' => $user,
    ]);
}

This controller will create a new user in the database, using the data from the request. It then formats the data into a response, which will be sent back to the client.

Formatting the Response

The final step is to format the response. This can be done using the JSON format. The following is an example of a response that includes the data from the UserController@store route:

{
    "data": {
        "id": 1,
        "name": "John Doe",
        "email": "[email protected]"
    }
}

This response contains the data of the newly created user. This can then be used by the client to display the data or use it in some other way.

Creating an API in Laravel is relatively easy. By defining a route, creating a controller, and formatting the response, an API can be quickly created. This will allow the client to access the data stored in the database, and use it in a variety of ways.

Answers (0)