In this article we will focus on the following things
1.Basics of RESTful API.
2.Create a new project using laravel 5.6.
3.How to write RESTful APIs.
RESTful API
REST stands for Representational State Transfer and is an architectural style for network communication between applications, which relies on a stateless protocol (usually HTTP) for interaction.
In RESTFUL web service HTTP methods like GET, POST, PUT and DELETE can be used to perform CRUD operations.REST is very simple compare to other methods like SOAP, CORBA, WSDL etc.
Our Services are Data Visualization | Ui/Ux Design
HTTP Methods
In RESTful APIs, we use the HTTP verbs as actions, and the endpoints are the resources acted upon. We will be using the HTTP verbs for their semantic meaning.
GET (Retrieve
resource)
POST (Create resource)
PUT (Update resource)
DELETE (Delete resource)
HTTP Status Codes
200 | OK |
201 | Created |
304 | Not Modified |
400 | Bad Request |
401 | Unauthorized |
403 | Forbidden |
404 | Not Found |
422 | Unprocessable Entity |
500 | Internal Server Error |
Installation
Install Laravel by using the Composer in your terminal
step1:$ composer create-project --prefer-dist laravel/laravel rest-api
After successful installation,
you should be able to start the server and test if everything is working
step2:$ php artisan serve
Laravel development server started: <http://127.0.0.1:8000>.
When you open this url in browser, you should be able to see the following laravel welcome page
create database and update your .env file
we can use the following command to generate database migration along with model
Step3:$ php artisan make:model User -m
It will create app/User.php and database/migrations/2018_02_05_061350_create_users_table.Edit the User.php,it should look as follows
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
/**
* User
*
* @version 1.0.0
* @since 1.0.0
* @author Uday Kumar
*
*/
class User extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Set the user's name.
*
* @param string $value
* @return void
*/
public function setNameAttribute($value)
{
return $this->attributes['name'] = ucfirst($value);
}
/**
* Set the password
*
* @param string $value
* @return void
*/
public function setPasswordAttribute($value)
{
return $this->attributes['password'] = Hash::make($value);
}
}
//end of class User
//end of file User.php
edit your database/migrations/2018_02_05_061350_create_users_table, it should
look like as follows
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
/**
* CreateUsersTable
*
* @version 1.0.0
* @since 1.0.0
* @author Uday Kumar
*
*/
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
//end of class CreateUsersTable
//end of file CreateUsersTable.php
Step4:$ php artisan migrate
Step5:$ php artisan make:request UserRequest
edit the Http/requests/UserRequest.php as follows
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
/**
* UserRequest
*
* @version 1.0.0
* @since 1.0.0
* @author Uday Kumar
*
*/
class UserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|max:127|unique:users,name',
'email' => 'required|email|max:127|unique:users,email',
'password' => 'required'
];
}
}
//end of class UserRequest
//end of file UserRequest.php
Step6:$ php artisan make:controller
User
Controller –resource edit your Http/Controllers/UserController as follows
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Http\Response;
use App\Http\Requests\UserRequest;
/**
* @access public
* @author Uday Kumar
* @version 1.0.0
*/
class UserController extends Controller {
protected $request;
protected $user;
/**
*
* @param Request $request
* @param Product $user
*/
public function __construct(Request $request, User $user) {
$this->request = $request;
$this->user = $user;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index() {
$user = $this->user->all();
return response()->json(['data' => $user,
'status' => Response::HTTP_OK]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(UserRequest $request) {
$data = $this->request->all();
$this->user->name = $data['name'];
$this->user->email = $data['email'];
$this->user->password = $data['password'];
$this->user->save();
return response()->json(['status' => Response::HTTP_CREATED]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update($id) {
$data = $this->request->all();
$user = $this->user->find($id);
$user->name = $data['name'];
$user->email = $data['email'];
$user->password = $data['password'];
$user->save();
return response()->json(['status' => Response::HTTP_OK]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id) {
$user = $this->user->find($id);
$user->delete();
return response()->json(['status' => Response::HTTP_OK]);
}
}
//end of class UserController
//end of file UserController.php
edit your routes/api.php as follows
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::resource('user', 'UserController');
Example:
GET
URL:http://127.0.0.1:8000/api/user
Response:
{
"data": [
{
"id": 1,
"name": "Uday kumar",
"email": "[email protected]",
"created_at": "2018-02-17 07:15:00",
"updated_at": "2018-02-17 07:18:54"
}
],
"status": 200
}
//----------------------------------------
POST
URL:http://127.0.0.1:8000/api/user
Request:
{
"name": "Uday kumar",
"email": "[email protected]",
"password": "xxxxxx"
}
Response:
{
"status": 201
}
//---------------------------------------
PUT/PATCH
URL:http://127.0.0.1:8000/api/user/1
Request:
{
"name": "uday kumar",
"email": "[email protected]",
"password": "xxxxxxx"
}
Response:
{
"status": 200
}
//---------------------------------------
DELETE
URL:http://127.0.0.1:8000/api/user/1
Response:
{
"status": 200
}