1. What is an API
API (Application Programming Interface) is a medium through which two software share data with each other. Example: When your mobile app fetches weather information from a weather service, it does so using API.
2. Type of APIs (RESTful, GraphQL, SOAP, etc)
APIs can be of different general types:
-
RESTful API: The most popular, uses the HTTP protocol. It have http method GET, PSOT,PUT, DELETE, PATCH. The GET method using featch the data from database, POST method using data store in database, PUT method using send data to the server to create a new resource. DELETE method is working remove from the server. The PATCH method partial update on a resourc.
-
GraphQL: You can work with as much data as you need from server. It is more and more prfessional way to data store and data fetch. It is more and more professional way to data store and data fetch.
-
SOAP: This technology using older strict API standard. web service API.There is API protocol, XML only,HTTP, SMTP.
3. Creating Laravel Project
Laravel is a popular PHP framework. To create an API, you first need to create a Laravel project. Command example:
composer create-project laravel/laravel project_name
4. API testing tool – Postman
5. Laravel APIs (CRUD operation)
Laravel can be used to create APIs that perform CRUD (Create, Read, Update, Delete) operations. Example: Creating a to-do list where items can be added, viewed, updated, and deleted.
6. Error Handling
If there is a problem or error in the API, it needs to be handled properly. For example, data not found, authorization failure, etc. Try-catch blocks or Exception handling are used in Laravel.
7. Authentication & Security
The API needs to be secured and authenticated. In general:
-
Token-based authentication: such as JWT (JSON Web Token).
-
API Key: Only specific users can use the API.
-
Rate Limiting & HTTPS: Protection from excessive requests or data theft.
Laravel Install
composer create-project "laravel/laravel:^10.0" example-app
API Setup
- controller
- api.php
- migration FIle
- model
1.1 Controller (Function to Return All Users)
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
class UserController extends Controller
{
// # function to Create Users
public function createUsers(Request $request)
{
// Validation
$validation = Validator::make($request->all(),[
'name' => 'required|string',
'email' => 'required|string|unique:users',
'phone' => 'required|numeric',
'password' => 'required|min:6',
]);
if ($validation->fails()) {
$result = [
'status' => false,
'message' => "Validation error occurred"
];
return response()->json($result, 400);
}
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'password' => bcrypt($request->password)
]);
if($user->id){
$result = array('status' => true, 'message'=> 'User Created Successfully', 'data' => $user);
$responseCode = 200;
}else{
$result = array('status' => false, 'message' => 'User is faild' );
$responseCode = 400;
}
return response()->json($result, $responseCode);
}
// # function to return all Users
public function getUsers(Request $request){
$users = User::all();
$result = array('status' => true, 'message' => count($users). "User(s) fetched",
"data" => $users);
$responseCode = 200; // Success
return response()->json($result, $responseCode);
}
// single product deatils view
public function getUserDetails($id)
{
$user = User::find($id);
if (!$user)
{
return response()->json(['status' => false, 'message' => "User not found", 400 ]);
}
$result = array('status'=> true, 'message'=>"user found","data"=>$user);
$responseCode = 200;
return response()->json($result, $responseCode);
}
}
2.1 API
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\UserController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('create-users', [UserController::class, 'createUsers']);
Route::get('get-users', [UserController::class, 'getUsers']);
Route::get('get-userDetails/{id}', [UserController::class, 'getUserDetails']);
3.1 Migration File
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('phone')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
}
};
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'phone',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
POST Man by API Injection
1. GET
2. POST method



0 Comments