How To Differentia Between Web And Api Routes In Laravel

admin_img Posted By Bajarangi soft , Posted On 18-01-2021

In Laravel we have two routes separate file one is web.php and api.php .So today we discuss what is the difference between web.php file and api.php file

How To Differentia Between Web And Api Routes In Laravel

Differentia Between Web And Api Routes In Laravel

Web.php API.php
The routes/webphp file defines routes that are used to build front end and backend also web interface. routes/apiphp file is used when you want to make a Restful API  and to  develope backend of project.
These routes are assigned the web middleware group, which provides features like
session state and CSRF protection.
The routes in routes/api are stateless and  does it mean api routing is not using session state, CSRF protection
Web routes, are used when we want to return views. Api routes, are used when we want to return json ( Api resource/collection ).
A web POST/PUT request would also create/update some entity but would usually return a redirect to a new page An API POST/PUT request would create/update some entity and return a JSON response, like a newly created model for POST, or an updated model for PUT
POST/PUT Routes in your web.php are called using a simple form. so the form submission will send your form-data to the given endpoint, and it will return the response directly to your browser This is useful in cases where you have javascript code calling an AJAX request. When you'd send data to your API endpoint, you should receive a status 200 with a JSON representation of the model you just created/updated. Your javascript code then decides what to do next, like closing a popup window
Example:
public function index()
{
    return view('home');// return to page
}
Example:
public function index()
{
    return response()->json($model);// response with status 
}

Related Post