Understanding APIs: Types and Creation
Understanding APIs: Types and Creation
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.
Category api’s
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
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
Example : header(‘content-type’:application/json);
Header(‘Access-Control-Allow-Origin:*’);
If ( mysqli_num_rows($result) > 0 ) {
$outpus = mysqli_fetch_assoc($result);
} else {
$array = [
];
header(‘content-type’:application/json);
Header(‘Access-Control-Allow-Origin:*’);
$conn = mysqli_connect(‘localhost’,’root’,’’,’databasename);
If ( mysqli_num_rows($result) > 0 ) {
$outpus = mysqli_fetch_assoc($result);
} else {
$array = [
];
API’s Creation (Specific Data Fetch Api’s using id) in core php
Example : header(‘content-type’:application/json);
Header(‘Access-Control-Allow-Origin:*’);
$fetchId = $data[‘sid’];
If ( mysqli_num_rows($result) > 0 ) {
$outpus = mysqli_fetch_assoc($result);
Echo Json_encode($output, true);
} else {
$array = [
];
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);
If ( mysqli_num_rows($result) > 0 ) {
$outpus = mysqli_fetch_assoc($result);
} else {
$array = [
];
}
API’s Creation ( Insert Api’s) in core php
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
);
$sfirstname = $data[‘sfirstname’];
$slastname = $data[‘slastname’];
$semail = $data[‘semail’];
If ( $resultOuput ) {
$array = [
];
$array = [
];
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’];
If ( $resultOuput ) {
$array = [
‘message’ => ‘New Record Not Created’,
];
} else {
$array = [
];
Update
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’];
If ( $resultOuput ) {
$array = [
];
} else {
$array = [
];
When i connect others server to this serve using method is called curl.
Curl function
$var2 = curl_init();
Curl_setopt($var2,CURLOPT_URL/CURLOPT_FILE,”[Link]
Curl_exec($var2);
Curl_close($var2);
Curl_setopt($ch,curlopt_url,$url);
Curl_setopt($ch,$curlopt_returntransfer,true);
$result(output) = curl_exce($ch);
Curl_close($ch);
$result = json_decord($result,true);
<script src="[Link]
key=AIzaSyBNSOfgS1wXKgSRwKHgJ5pPTTlVnziSWeg&libraries=places "></script>
[Link]/home/dashboard
Step 4): create projects
Step 5): API’s and services Library Maps Javascript api select and press enable buttons
AIzaSyBiGLZtS1RBMyizULhZskWvj6CdeuSiDHE
<!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] )
User type External app name user support email emailaddress save data
Step 3): Crendentials create Oauth client Id select application web application
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();
}
$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');
}
$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>";
}
}
?>
// }
// }
} 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');
}
[Link]
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',
]);
}
}
}
}
$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(){
// 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
<?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;
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
Routes
$routes->get("api/getUsers","OauthUserController::getUsers",['filter' =>
'auth']);
Important jwt rest api with token “ [Link]
codeigniter-php “
“ [Link] “
“ [Link] “
<?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];
}
$jwt = JWT::encode($payload,$key,$arg);
return $jwt;
}
<?php
namespace App\Filters;
use App\Models\ApiTable;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;
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)
{
//
}
$routes->get('/printData','AdminController::printData',['filter' =>
'jwt']);
[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
try {
helper('jwt');
$encodedToken = getJWTFromRequest($authenticationHeader);
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'
// ]);
}
return Services::response()
->setJSON(
[
'error' => $e->getMessage()
]
)
->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
}
}
<?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));
}
}
<?php
namespace App\Controllers;
use App\Libraries\Oauth;
use OAuth2\Request;
use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\HTTP\ResponseInterface;
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 ?