0% found this document useful (0 votes)
14 views30 pages

Understanding APIs: Types and Creation

An API (Application Programming Interface) allows applications to communicate with each other by sending requests and receiving data, typically in JSON or XML format. It includes various types such as Open APIs, Partner APIs, and Internal APIs, and can use different protocols like REST and SOAP, with REST being the most popular due to its flexibility and ease of use. The document also provides examples of API creation in PHP, the use of cURL for connecting to other servers, and implementing Google APIs for functionalities like autocomplete and OAuth authentication.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views30 pages

Understanding APIs: Types and Creation

An API (Application Programming Interface) allows applications to communicate with each other by sending requests and receiving data, typically in JSON or XML format. It includes various types such as Open APIs, Partner APIs, and Internal APIs, and can use different protocols like REST and SOAP, with REST being the most popular due to its flexibility and ease of use. The document also provides examples of API creation in PHP, the use of cURL for connecting to other servers, and implementing Google APIs for functionalities like autocomplete and OAuth authentication.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What is api?

Application program interface is get request in (android, iphone me apps) this request is collect by api
and transfer your request such as form of xml, json form when server ssend require data api will be send
this form of xml, json. Mostly use json because it’s light weight and faster.

Real time example using api’s

 Login with facebook / google.


 Map
 SMS
 Payment gateways
 Weather
 Email
 Courier / Shipping
 Booking system
 Chatting
 Video / images
 Searches

Category api’s

 Open API’s ( Free API’s )


 Partner API’s (Paid API’s)
 Internal API’s ( Personal API’s )

Type of HTTP Protocol

 SOAP
 XML-RPC
 JSON-RPC
 REST

REST API’s (Representational State Transfer) is most popular api’s because it support different formats
like (JSON, XML, Text, User-defined). But SOAP Api support only xml format

REST API’s Advantages

 Easy to use
 Support different format like (JSON, XML, Text, User-defined).
 HTTP Method (Get, Put & patch, Post, Delete).
 Header(‘content-type:application/json”); is important to display page
 Header(Access-Control-Allow-Methods:PUT’) optional
 Header(‘Access-Control-Allow-Origin:* means every one can use it); if you want specific website
use this api’s then * ki jga is website ka name dna h. its use security purpose.
 Header (‘Access-Control-Allow-Headers:<headername>) option and use security purpose

API’s Creation (All Data Fetch Api’s) in core php


Step 1): add headers

Example : header(‘content-type’:application/json);

Header(‘Access-Control-Allow-Origin:*’);

Step 2): connection connections

Example : $conn = mysqli_connect(‘localhost’,’root’,’’,’databasename);

Step 3): fetch data using php query

Example : $sqliQuery = “select * from tablename”;

$resultOuput = mysqli_query($conn, $sqliQuery);

If ( mysqli_num_rows($result) > 0 ) {

$outpus = mysqli_fetch_assoc($result);

Echo Json_encode($output, true);

} else {

$array = [

‘message’ => ‘not data founded, table is empty’ ,

‘status => false,

];

Echo json_encode($array, true);

Complete api for all data fetch is :

header(‘content-type’:application/json);

Header(‘Access-Control-Allow-Origin:*’);

$conn = mysqli_connect(‘localhost’,’root’,’’,’databasename);

$sqliQuery = “select * from tablename”;

$resultOuput = mysqli_query($conn, $sqliQuery);

If ( mysqli_num_rows($result) > 0 ) {
$outpus = mysqli_fetch_assoc($result);

Echo Json_encode($output, true);

} else {

$array = [

‘message’ => ‘not data founded, table is empty’ ,

‘status => false,

];

Echo json_encode($array, true);

API’s Creation (Specific Data Fetch Api’s using id) in core php

Step 1): add headers

Example : header(‘content-type’:application/json);

Header(‘Access-Control-Allow-Origin:*’);

Step 2): connection connections

Example : $conn = mysqli_connect(‘localhost’,’root’,’’,’databasename);

Step 3): json to convert array form

Example : $data = json_decord(file_get_content(“php://input”),true);

$fetchId = $data[‘sid’];

Step 4): fetch data using php query

Example : $sqliQuery = “select * from tablename where id = $fetchId”;

$resultOuput = mysqli_query($conn, $sqliQuery);

If ( mysqli_num_rows($result) > 0 ) {

$outpus = mysqli_fetch_assoc($result);
Echo Json_encode($output, true);

} else {

$array = [

‘message’ => ‘not data founded, table is empty’ ,

‘status => false,

];

Echo json_encode($array, true);

Complete api for Specific data fetch is using id :

header(‘content-type’:application/json);

Header(‘Access-Control-Allow-Origin:*’);

$data = json_decord(file_get_content(“php://input”),true);

$fetchId = $data[‘sid’];

$conn = mysqli_connect(‘localhost’,’root’,’’,’databasename);

$sqliQuery = “select * from tablename where id = $fetchId”;

$resultOuput = mysqli_query($conn, $sqliQuery);

If ( mysqli_num_rows($result) > 0 ) {

$outpus = mysqli_fetch_assoc($result);

Echo Json_encode($output, true);

} else {

$array = [

‘message’ => ‘not data founded, table is empty’ ,

‘status => false,

];

Echo json_encode($array, true);

}
API’s Creation ( Insert Api’s) in core php

Step 1): add headers

Example : header(‘content-type’:application/json);

Header(‘Access-Control-Allow-Origin:*’);

Header(‘Access-Control-Methods: POST’);

Header(‘Access-Control_header:

Access-Control_header,

Access-Control-Methods,

Authorization,

x-Requested-With

);

Step 2): decode json file to array ddata

Example : $data = json_decord(file_get_content(“php://input”),true);

$sfirstname = $data[‘sfirstname’];

$slastname = $data[‘slastname’];

$semail = $data[‘semail’];

Step 3): $sqliQuery = “insert into tablename (‘firstname’,’lastname’,’email’) values ‘{sfirstname}’,’


{slastname}’,’ {semail}’”;

$resultOuput = mysqli_query($conn, $sqliQuery);

If ( $resultOuput ) {

$array = [

‘message’ => ‘New Record Not Created’,

‘status => true,

];

Echo json_encode($array, true);


} else {

$array = [

‘message’ => ‘New Record Is Not Created’,

‘status => false,

];

Echo json_encode($array, true);

Complete insert api’s

header(‘content-type’:application/json);

Header(‘Access-Control-Allow-Origin:*’);

Header(‘Access-Control-Methods: POST’);

Header(‘Access-Control_header:

Access-Control_header,

Access-Control-Methods,

Authorization,

x-Requested-With

);

$conn = mysqli_connect(‘localhost’,’root’,’’,’databasename);

$data = json_decord(file_get_content(“php://input”),true);

$sfirstname = $data[‘sfirstname’];

$slastname = $data[‘slastname’];

$semail = $data[‘semail’];

$sqliQuery = “insert into tablename (‘firstname’,’lastname’,’email’) values ‘{sfirstname}’,’


{slastname}’,’ {semail}’”;

$resultOuput = mysqli_query($conn, $sqliQuery);

If ( $resultOuput ) {

$array = [
‘message’ => ‘New Record Not Created’,

‘status => true,

];

Echo json_encode($array, true);

} else {

$array = [

‘message’ => ‘New Record Is Not Created’,

‘status => false,

];

Echo json_encode($array, true);

Update

Complete update api’s

header(‘content-type’:application/json);

Header(‘Access-Control-Allow-Origin:*’);

Header(‘Access-Control-Methods: PUT’);

Header(‘Access-Control_header:

Access-Control_header,

Access-Control-Methods,

Authorization,

x-Requested-With

);

$conn = mysqli_connect(‘localhost’,’root’,’’,’databasename);

$data = json_decord(file_get_content(“php://input”),true);

$sid = $data[‘sid’];

$sfirstname = $data[‘sfirstname’];
$slastname = $data[‘slastname’];

$semail = $data[‘semail’];

$sqliQuery = “update tablename SET firstname = ‘{$sfirstname}’, lastname = ‘{$slastname}’, email = ’


{$semail}’ where id = ‘{$sid}’ ”;

$resultOuput = mysqli_query($conn, $sqliQuery);

If ( $resultOuput ) {

$array = [

‘message’ => ‘Record Updated’,

‘status => true,

];

Echo json_encode($array, true);

} else {

$array = [

‘message’ => ‘Record Is Not updated’,

‘status => false,

];

Echo json_encode($array, true);

What is curl in api’s and using 3rd party api’s

When i connect others server to this serve using method is called curl.

Curl function

 Curl init(); // insilization data


 Curl_setcot(); // to send data localhost to other server
 Curl_exec(); // for execute
 Curl_close() //
Examples:

$var2 = curl_init();

Curl_setopt($var2,CURLOPT_URL/CURLOPT_FILE,”[Link]

CURL_SETOPT($VAR,CURLLOPT_RETURNTRANSFER,true); IS KI HELP MILNY VALY DATA KSI VARABLE ME


STORE KRWA SKTY HAIN.

CURL_SETOPT($VAR,CURLLOPT_POSTFIELD,true); IS KI HELP hm data ko post ki help sy data bj skty hain.

Curl_exec($var2);

Curl_close($var2);

Real life example:

$url = “your api url link”;

$ch = curl init();

Curl_setopt($ch,curlopt_url,$url);

Curl_setopt($ch,$curlopt_returntransfer,true);

$result(output) = curl_exce($ch);

Curl_close($ch);

// convert json to array

$result = json_decord($result,true);

How to implement google place auto complete api in codenator 4

Step 1): Add Script Link In Your HTML Files

<script src="[Link]
key=AIzaSyBNSOfgS1wXKgSRwKHgJ5pPTTlVnziSWeg&libraries=places "></script>

Key = your api key

Step 2): find key api key in google cloud account

[Link]/home/dashboard
Step 4): create projects

Step 5): API’s and services  Library  Maps Javascript api  select and press enable buttons

Step 6): API’s and services  crendentails  create credentials  “


AIzaSyBNSOfgS1wXKgSRwKHgJ5pPTTlVnziSWeg ”

AIzaSyBiGLZtS1RBMyizULhZskWvj6CdeuSiDHE

Step 7): application

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<script
src="[Link]
script>
<link
href="[Link]
.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65Vohhpu
uCOmLASjC" crossorigin="anonymous">
<script
src="[Link]
[Link]" integrity="sha384-
MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
<title>Document</title>
</head>
<body>
<div class="mt-3 px-4">
<input type="text" name="" id="search_input" class="form-control"
placeholder="Search Address">
</div>
<script>
var searchInput = 'search_input';
$(document).ready(function(){
var autocomplete;
autocomplete = new
[Link](([Link](searchInput)), {
types: ['geocode']
});
});
</script>
<script src="[Link]
key=AIzaSyBiGLZtS1RBMyizULhZskWvj6CdeuSiDHE&libraries=places"></script>

</body>
</html>

Create project sign with google FOR LARAVE FLOOW THIS VIDEO ( [Link]
v=aHiPXhI4Ljc ) and code nator 4 me ( [Link] )

Step 1): create new project :

Step 2): Oauth consent screen go to page

User type  External  app name  user support email  emailaddress  save data

Step 3): Crendentials  create Oauth client Id  select application web application

Step 4): save "client_id":"482350107066-


[Link]","project_id"
:"oceanic-will-420411","auth_uri":"[Link]
auth","token_uri":"[Link]
token","auth_provider_x509_cert_url":"[Link]
v1/certs","client_secret":"GOCSPX-
VQOTqAVM2n4tmMDTbJV1G4ZYPLnP","redirect_uris":["[Link]
registerPage"],"javascript_origins":["[Link]

Step 4): run commands : composer require google/apiclient:^2.7

private $googleClient=NULL;
public function __construct(){
// require_once APPPATH. "libraries/vendor/[Link]";
$this->bloodGroup = new BloodGroupModel();
// $this->Users = Sentinel::getUser()->findAll();
$this->googleClient = new \Google_Client();
$this->googleClient->setClientId("636714333861-
[Link]");
$this->googleClient->setClientSecret("GOCSPX-
eiylYT0MeFyiLk2i2lj7XS7ZofRw");
$this->googleClient-
>setRedirectUri("[Link]
$this->googleClient->addScope("email");
$this->googleClient->addScope("profile");
$this->Users = new User();
}

public function loginWithGoogle()


{

$db = \Config\Database::connect();
$token = $this->googleClient->fetchAccessTokenWithAuthCode($this-
>request->getVar('code'));
if (!isset($token['error'])){
$this->googleClient->setAccessToken($token['access_token']);
session()->set("AccessToken", $token['access_token']);
$googleService = new Oauth2($this->googleClient);
$data = $googleService->userinfo->get();
$currentData = date("Y-m-d H:i:s");
// echo "<pre>";
// print_r($data);
// echo "</pre>";
// die();
$userdata = array();
if ($this->Users->isAlreadyRegister($data['id'])){
$userdata = [
'first_name' => $data['givenName'],
'last_name' => $data['familyName'],
'email' => $data['email'],
'updated_at' => $currentData,
];
$this->Users->updateUserData($userdata, $data['id']);
$userUser = $db->table('users')->where('email',
$data['email'])->get();
$userType = $userUser->getRowArray()['user_type'];
if ($userType == 'admin') {
return redirect()->to('/adminDashboard');
} else if ($userType == 'donor') {
return redirect()->to('/donorDashboard');
} else if ($userType == 'user') {
return redirect()->to('/userDashboard');
}
} else {
$userdata = [
'oauth_id' => $data['id'],
'first_name' => $data['givenName'],
'last_name' => $data['familyName'],
'email' => $data['email'],
'updated_at' => $currentData,
'created_at' => $currentData,

];
$this->Users->insertUserData($userdata);
}
session()->set("LoggedUserData",$userdata);
return redirect()->to('/googleUpdatePage');
} else {
session()->setFlashData("Error", "Something went Wrong");
return redirect()->to('/loginPage');
}

// register page me <?=session()->get("loggedUserData)['name']?


session()->get("loggedUserData)['name']:''
// }
}

public function isAlreadyRegister($authid){


return $this->db->table('users')->getWhere(['oauth_id' =>
$authid])->getRowArray() > 0 ? true : false;
}

public function updateUserData($userdata, $authid){


$this->db->table('users')->where(['oauth_id' => $authid])-
>update($userdata);
// $user = Sentinel::findByOauthId($authid);
// $user->update($userdata);
}

public function insertUserData($userdata){


$register = $this->db->table('users')->insert($userdata);
$oauthid = $userdata['oauth_id'];
$userFind = $this->db->table('users')->where('oauth_id',
$oauthid)->get();

$userId = $userFind->getRowArray()['id'];
$user = Sentinel::findById($userId);
// $activation = Activation::create($user);
// $completed = Activation::complete($user, $activation->code);
// echo "<pre>";
// print_r($userFind);
// echo "</pre>";
// die();
}
<?php
if (session()->has("LoggedUserData")) {
echo "<p class='mt-3'>Welcome, " . session()-
>get("LoggedUserData")['first_name'] . "</p>";
} else {
if (Sentinel::check()) {
$user = Sentinel::getUser();
echo "<p class='mt-3'>Welcome, " . $user-
>first_name . "</p>";
}
}
?>

<?php echo $googleButton; ?>

And logout function is

public function logout(){


$session = \Config\Services::session();

if (session()->has("LoggedUserData") && session()-


>has("AccessToken")) {
// // for google login user
// $user = Sentinel::getUser();
// $userId = $user->id;
// $logout = Sentinel::logout($user, true);
// if ($logout) {
session()->remove('LoggedUserData');
session()->remove('AccessToken');
return redirect()->to('/loginPage');
// if (!(session()->get('LoggedUserData') &&
session()->get('AccessToken'))){

// }

// }
} else {
if (Sentinel::check()) {
// for non google login user
$user = Sentinel::getUser();
$userId = $user->id;
$logout = Sentinel::logout($user, true);
if ($logout) {
return redirect()->to('/loginPage');
}
}
}

this->Users->updateUserData($userdata, $data['id']);
$userUser = $db->table('users')->where('email',
$data['email'])->get();
$userType = $userUser->getRowArray()['user_type'];
if ($userType == 'admin') {
session()->set("LoggedUserData",$userdata);
return redirect()->to('/adminDashboard');
} else if ($userType == 'donor') {
session()->set("LoggedUserData",$userdata);
return redirect()->to('/donorDashboard');
} else if ($userType == 'user') {
session()->set("LoggedUserData",$userdata);
return redirect()->to('/userDashboard');
}

How to fing lag

[Link]

API CREATE, AUTHRIZATION, API TOKEN MANAGEMENT SYSTEM, PHP JWT

1) API AUTHRIZATION SORCE VIDEO LINK “ [Link] “


2) API JWT AUTHRIZATION SOURCE LINK “ [Link]
tutorial-restful-api-jwt-authentication-d5963d797ec4 “
3) LIBRARY JWT API “ [Link] “

CREATE REST API JWT AUTHRIZATION USING COTENATOR 4


Step 1): create user model and user controller

Step 2):

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\User;
use CodeIgniter\API\ResponseTrait;
class OauthUserController extends BaseController
{
use ResponseTrait;
public function createOauthUser(){
$createUser = new User();
$data=[
'first_name' => $this->request->getVar('first_name'),
'last_name' => $this->request->getVar('last_name'),
'email' => $this->request->getVar('email'),
'password' => password_hash($this->request-
>getVar('password'),PASSWORD_DEFAULT),
];
$alreadyData = $createUser->where('email',$this->request-
>getVar('email'))->first();
if ($alreadyData) {
return $this->respondCreated([
'status' => '0',
'message' => 'this data is already availible',
]);
} else {
$newUsers = $createUser->save($data);
if ($newUsers) {
return $this->respondCreated([
'status' => '1',
'message' => 'New User Is created',
]);
} else {
return $this->respondCreated([
'status' => '0',
'message' => 'New User Is not created',
]);
}
}
}
}

Step 3): route file

$routes->post('/api/
createOauthUser','OauthUserController::createOauthUser');

Step 4): is function me wo data jis ko jwt me convert krna chty hain is data ko lkhna h example

// login users
public function loginUser(){

$loginUser = new User();


$data=[
'email' => $this->request->getVar('email'),
'password' => password_hash($this->request-
>getVar('password'),PASSWORD_DEFAULT),
];
$verifyUserEmail = $loginUser->where('email',$this->request-
>getVar('email'))->first();
if ($verifyUserEmail) {
$verifyPassword = password_verify($this->request-
>getVar('password'),$verifyUserEmail['password']);
// return $this-
>respondCreated($verifyUserEmail['password']);
if ($verifyPassword) {
$key = "khawajaafaqahmedawan";
$payload = [
"iss" => "localhost",
"aud" => "localhost",
"data" => [
'user_id' => $verifyUserEmail['id'],
'email'=> $verifyUserEmail['email'],
'first_name' => $verifyUserEmail['first_name'],
'last_name' => $verifyUserEmail['last_name'],
],
];
$jwt = JWT::encode($payload,$key,'HS256');
return $this->respondCreated([
'status' => '1',
'jwt' => $jwt,
'message' => $verifyUserEmail['first_name'].' is
Login ',
]);
} else {
return $this->respondCreated([
'status' => '0',
'message' => 'InValid Password',
]);
}
} else {
return $this->respondCreated([
'status' => '0',
'message' => 'email is not founded',
]);
}
}

Is function me wo data is ko decord jwt sy krna chty hain

public function getUsers(){


$request = service('request');
$key = "khawajaafaqahmedawan";
$token = $request->getHeader('Authorization');
$jwt = $token->getValue();
$decordUserdata = JWT::decode($jwt,new Key($key,'HS256'));
$userDaata = $decordUserdata->data;
return $this->respond([
'status' => '1',
'users' => $userDaata,
]);
}

Jwt encode data

// jwt data encode


$key = "88643846"; // is ki ja mtlb yh h jwt me ko data
hm set krna chty hain is data ko access krny k ly secrect key h.
$payload = [
'iss' => 'localhost',
'aud' => 'localhost',
'data' => ([
'first_name ' => 'my name is '.
$verifyUserEmail['first_name'] . '' . $verifyUserEmail['last_name'],
'email' => 'my name is '.
$verifyUserEmail['email'],
'id ' => 'my name is '.
$verifyUserEmail['id'],
]),
];
$jwt = JWT::encode($payload,$key,'HS256');
return $this->respondCreated([
'status' => '1',
'jwt' => $jwt,
'message' => 'Login Successfully',
]);
// jwt data encode

Jwt decord data

// jwt decord
$request = service('request');
$key = "88643846"; // yh wo key jo hm sy jwt encode krty
waqt set ki thi
$token = $request->header('Authorization'); // yh wo token ho ga
jwt encode krty waqt hm mla tha jwt ki form me
$valueGetThroughToken = $token->getValue(); // $token sy milny
wala daaata
$decordvalueGetThroughToken = JWT::decode($valueGetThroughToken,
new Key($key,'HS256')); // is data ko decode kya
$fetchData = $decordvalueGetThroughToken->data;
return $this->respond([
'status' => 1,
'data' => $fetchData,
]);
// jwt decord

Step 5): run command “ php spark make:filter AuthFilter

<?php

namespace App\Filters;

use Exception;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;

class AuthFilter implements FilterInterface


{
/**
* Do whatever processing this filter needs to do.
* By default it should not return anything during
* normal execution. However, when an abnormal state
* is found, it should return an instance of
* CodeIgniter\HTTP\Response. If it does, script
* execution will end and that Response will be
* sent back to the client, allowing for error pages,
* redirects, etc.
*
* @param RequestInterface $request
* @param array|null $arguments
*
* @return RequestInterface|ResponseInterface|string|void
*/
public function before(RequestInterface $request, $arguments = null)
{
// $key = getenv('JWT_SECRET');
$request = service('request');
$key = "88643846";
$header = $request->header('Authorization');
$token = $header->getValue();

// extract the token from the header


if(!empty($header)) {
if (preg_match('/Bearer\s(\S+)/', $header, $matches)) {
$token = $matches[1];
}
}

// check if token is null or empty


if(is_null($token) || empty($token)) {
$response = service('response');
$response->setBody('Access denied');
$response->setStatusCode(401);
return $response;
}

try {
// $decoded = JWT::decode($token, $key, array("HS256"));
$decoded = JWT::decode($token, new Key($key, 'HS256'));
} catch (Exception $ex) {
$response = service('response');
$response->setBody('Access denied');
$response->setStatusCode(401);
return $response;
}
}

/**
* Allows After filters to inspect and modify the response
* object as needed. This method does not allow any way
* to stop execution of other after filters, short of
* throwing an Exception or Error.
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @param array|null $arguments
*
* @return ResponseInterface|void
*/
public function after(RequestInterface $request, ResponseInterface
$response, $arguments = null)
{
//
}
}

Filter file me

public array $aliases = [


'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'cors' => Cors::class,
'forcehttps' => ForceHTTPS::class,
'pagecache' => PageCache::class,
'performance' => PerformanceMetrics::class,
'auth' => AuthFilter::class,
];

Routes

$routes->get("api/getUsers","OauthUserController::getUsers",['filter' =>
'auth']);
Important jwt rest api with token “ [Link]
codeigniter-php “

Api key and hit limit token

“ [Link] “

Coding style sheet

“ [Link] “

How to create filter jwt apis

Step 1): create helper function file is

<?php

use App\Models\User;
use Config\Services;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Google\Service\AppHub\Service;
use Cartalyst\Sentinel\Native\Facades\Sentinel;

function getJWTFromRequest($authenticationHeader){
if (is_null($authenticationHeader)) {
throw new Exception('Enter Your API Key');
}
return explode(' ',$authenticationHeader)[1];
}

function validateJWTFromRequest(string $encodedToken)


{
$arg = 'HS256';
$key = Services::getSecretKey();
if (empty($encodedToken)) {
throw new Exception('Enter Your API Key');
} else {
try {;
$decodedToken = JWT::decode($encodedToken, new Key($key,
$arg));
$user = Sentinel::findByEmail($decodedToken->email);
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}

function getSignedJWTForUser(string $email){


$arg = 'HS256';
$key = Services::getSecretKey();
$issuedAtTime = time();
$tokenTimeToLive = getenv('JWT_TIME_TO_LIVE');
$tokenExpiration = $issuedAtTime + $tokenTimeToLive;
$payload = [
'email' => $email,
'iat' => $issuedAtTime,
'exp' => $tokenExpiration,
];

$jwt = JWT::encode($payload,$key,$arg);
return $jwt;
}

Step 2): create filter file in filter folder

<?php

namespace App\Filters;

use App\Models\ApiTable;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;

class JWTAuthenticationFilter implements FilterInterface


{
/**
* Do whatever processing this filter needs to do.
* By default it should not return anything during
* normal execution. However, when an abnormal state
* is found, it should return an instance of
* CodeIgniter\HTTP\Response. If it does, script
* execution will end and that Response will be
* sent back to the client, allowing for error pages,
* redirects, etc.
*
* @param RequestInterface $request
* @param array|null $arguments
*
* @return RequestInterface|ResponseInterface|string|void
*/
public function before(RequestInterface $request, $arguments = null)
{
$authenticationHeader = $request-
>getServer('HTTP_AUTHORIZATION');

try {

helper('jwt');
$encodedToken = getJWTFromRequest($authenticationHeader);
//
$apiToken = new ApiTable();
$apiToken = $apiToken->where('token', $encodedToken)-
>first();
if (count($apiToken) > 0) {
return $request;
} else {
return response([
'error' => 'Token Key Is Invalid Try Correct Token'
]);
}
} catch (\Exception $e) {

return Services::response()
->setJSON(
[
'error' => $e->getMessage()
]
)
->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);

}
}

/**
* Allows After filters to inspect and modify the response
* object as needed. This method does not allow any way
* to stop execution of other after filters, short of
* throwing an Exception or Error.
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @param array|null $arguments
*
* @return ResponseInterface|void
*/
public function after(RequestInterface $request, ResponseInterface
$response, $arguments = null)
{
//
}

Step 3): app\config\service me add function add krna h

public static function getSecretKey(){


return getenv('JWT_SECRET_KEY');
}

Step 4): app\config\filter file me add krna h

'jwt' => JWTAuthenticationFilter::class,

public array $filters = [];

Step 5): routes files me

$routes->get('/printData','AdminController::printData',['filter' =>
'jwt']);

Step 6): printData

public function printData(){


echo "print data";
}

Step 7): finaly check post man software

[Link]
codenator 4 ka asa function js me valid token or request count , limit ho madee nazar rkh kr yh filter ka
function design kya gya h

public function before(RequestInterface $request, $arguments = null)


{
$authenticationHeader = $request-
>getServer('HTTP_AUTHORIZATION');

try {

helper('jwt');
$encodedToken = getJWTFromRequest($authenticationHeader);

$apiToken = new ApiTable();


$apiToken = $apiToken->where('token', $encodedToken)-
>first();

if (count($apiToken) > 0) {
$apiId = $apiToken['id']; // api record
id found
$count_request = $apiToken['count_request']; // api
record old count request found
$limit_request = $apiToken['limit_request']; // api
limit request
$apiStatus = $apiToken['status']; // api
activated status
$newHitCount = $count_request + 1; // new count
request

if ($apiStatus == 0) {
return Services::response()
->setJSON(
[
'error' => 'api is not working because it
deactivated'
]
)
->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
// return response([
// 'error' => 'Your Request Limit Is Over'
// ]);
} else {
if ($count_request < $limit_request) {
if ($count_request === $limit_request) {
$values = [
'status' => 0,
'updated_at' => date('Y-m-d h:i:s')
];
$db = \Config\Database::connect();
$updateApiRecord = $db->table('api_token')-
>where('id', $apiId)->update($values);
} else if ($count_request < $limit_request) {

$values = [
'count_request' => $newHitCount,
'updated_at' => date('Y-m-d h:i:s')
];
$db = \Config\Database::connect();
$updateApiRecord = $db->table('api_token')-
>where('id', $apiId)->update($values);
if ($updateApiRecord) {
return $request;
}
}
} else {
return Services::response()
->setJSON(
[
'error' => 'Your Request Limit Is Over'
]
)
->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
// return response([
// 'error' => 'Your Request Limit Is Over'
// ]);
}
}
} else {
return Services::response()
->setJSON(
[
'error' => 'Token Key Is Invalid Try Correct
Token'
]
)
->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
// return response([
// 'error' => 'Token Key Is Invalid Try Correct
Token'
// ]);
}

} catch (\Exception $e) {

return Services::response()
->setJSON(
[
'error' => $e->getMessage()
]
)
->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);

}
}

OAUTH API CODENATOR REST API

STEP 1): composer require bshaffer/oauth2-server-php "^1.10"


Migration files create

Step 2): create library files [Link]

<?php

namespace App\Libraries;

use OAuth2\Server;
use OAuth2\Storage\Pdo;

class Oauth{
var $server;
function __construct(){
$this->init();
}

function init(){
$dsn = getenv('[Link]');
$username = getenv('[Link]');
$password = getenv('[Link]');
$storage = new Pdo([
'dsn' => $dsn,
'username' => $username,
'password' => $password,
]);
$this->server = new Server($storage);
$this->server->addGrantType(new \OAuth2\GrantType\
UserCredentials($storage));
}
}

Step 3): create userController file

<?php

namespace App\Controllers;

use App\Libraries\Oauth;
use OAuth2\Request;
use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\HTTP\ResponseInterface;

class UserController extends BaseController


{
use ResponseTrait;
//
public function login(){
$oauth = new Oauth();
$resquest = new Request();
$response = $oauth->server->handleTokenRequest($resquest-
>createFromGlobals());
$code = $response->getStatusCode();
$body = $response->getResponseBody();
return $this->respond(json_decode($body),$code);
}
}

Step 4): $routes->post('/login','UserController::login');


Step 5): filter file create

public function before(RequestInterface $request, $arguments = null)


{
//
$oauth = new Oauth();
$request = Request::createFromGlobals();
$response = new Response();
if (!$oauth->server->verifyResourceRequest($request)){
$oauth->server->getResponse()->send();
die();
}
}

Step 6): $routes->get('/displayMessage','UserController::displayMessage',


['filter' => 'authFilter']);

Online doctor & hospital management system demo video “


[Link]

Project idea : [Link]

Static $variable

Static member ka banefit yh h k hm bna koi object bny is $variable ko use kr skty hain

How to use it ?

1) Classname::$variable name ya classname::functionname()


2) public Static function functionname(){$this->data ki jaga self::data lkh skty hain}
3) class personal{public static $name = “abc”;} class personal extends accounts( public function
show(){echo parent::$name;})

You might also like