Reputation: 3330
I have a laravel
project, which is about Students and their courses.
This project has CRUD
functions, where the user(mainly the school's admin) can create users and assign their courses. I have successfully created this project.
But now how do I make this an API?. I need to share the students courses to another website, therefore I need to create an API right?
I have never created an API in laravel
, when I checked the documentation of Laravel, it has this topic called API authentication using passport
, is this talking about requiring users to login first before accessing the API
?.
Would be very helpful if someone can explain a little bit about creating an API and where to start from.
Upvotes: 1
Views: 3442
Reputation: 13259
You are trying to give another website access to view the students courses. Is the data publicly available ? If yes, you don't need Authentication. But that means literally everybody with the API URL can access the data. Using Authentication on your API is entirely up to you.
Now, to create an API, it's very easy with Laravel. There are tons of free resources online like this one: https://tutorials.kode-blog.com/laravel-5-rest-api. Just google the topic for more.
Basically, the API works exactly like what you did in terms of controller and routing. In laravel 5.4, there is a separate route file for api located in routes/api.php
. That's where you define your routes.
Route::get('courses', 'Api\CourseController@index');
This route will respond to https://www.website.com/api/courses
and will link to the function index()
located in app/Http/Controllers/Api/CourseController.php
. You will have to create that controller yourself.
Looking at that route file, you can see something out of the box
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
It means the route /api/user
will require authentication because of the auth:api
middleware.
In your controllers so far, you return views. In api controller you will return response
public function index()
{
$courses = Course::all();
return response()->json($courses);
}
The application calling the website will receive a JSON object containing an array of courses. More about responses here: https://laravel.com/docs/5.4/responses
About api_token
The default API authentication offered by laravel works by checking api_token
attribute from the users table. That api_token has to been present in the headers of the request sent to the api. Laravel will then use that api_token to identify the user making the request. In default application, to get a user, you do
$user = Auth::user();
Within your API controllers, you do
$user = Auth::guard('api')->user();
//Auth will look for api_token to get the user making the request
Upvotes: 2