SlideShare a Scribd company logo
CONTINUE PART 2 : USING REMOTE
APIS
2- GUZZLE
WHAT IS GUZZLE ?
Guzzle is a PHP HTTP client that makes it easy to
send HTTP requests and trivial to integrate with
web services.
Secondly, Guzzle provides a very clean API to work
with. Documentation is very important when
working with a library.Guzzle has done a very good
job by providing a comprehensive documentation
INSTALLING GUZZLE USING COMPOSER
Wait a minute what is composer ????
OVERVIEW OF COMPOSER
● It's a dependancy manager tool it is used
everywhere in the PHP World. All large
and well-known website components in
other ward it will help you do the
following :
● 1- Install 3rd party php tools and
framewords
● 2- Update version of the tools you use
● 3- Auto load your own code (so in the
future you will only use composer‘s
autoloader!!! Cool ?
●
● Composer has two separate elements :
✔ The first is Composer itself which is a
command line tool for grabbing and installing
what you want to install.
✔ The second is Packagist - the main composer
repository. This is where the packages you
may want to use are stored.
✔ Every thing Composer installs does that in a
directory names vendor which shouldn‘t has
any of your code
WORKING WITH COMPOSER
 Working with composer will has only 3 task types :
 1- Define what you want to install (frame work or tool) in json format file
 2- Define where your classes files and configuration file or in the future name
spaces which you want to load in json file
 3- Some command files to make composer run the settings you define
 4- Require the autoloader of composer in your code
WORK SEQUENCE
1
•First Step
•Prepare composer.JSON File to tell composer what you want to install
2
•Second Step
•Prepare composer.json file about your autoload options
3
•Third step
•Run composer install command
1 & 2 COMPOSER.JSON FILE
PREPARATION
The Composer.JSON has
two sections :
 Require : The tools that you
want Composer to install
 Autoload : where are your
classes and configuration files
for composer to load , in the
future that will be using name
space not classmap.
COMMAND LINE
 Composer selfupdate
 Composer install
 Composer dump-autoload
 Note :
 When call composer install composer
will add some files and a directory with
name vendor in which all 3rd party tools
are
Composer dump-autoload
IN THE CODE
Require auto uploader
SAME WEATER EXAMPLE USING GUZZLE
USING GUZZLE YOU CAN DO ASYNC AND
CONCURRENT REQUESTS
<<ADVANCED BEGIN>>
ASYNCH VS SYNCH
CALL AN API ASYNCH
CONCURRENT REQUESTS TO MULTIPLE
APIS
USING GUZZLE YOU CAN DO ASYNC AND
CONCURRENT REQUESTS FINISHED
<<ADVANCED FINISHED>>
PART 3 : REST APIS
REST has become the default for most Web and
mobile apps, 70% of public API are RESTFUL
CONCEPTS >> BIG PICTURE >> CODE
CODE IS SO EASY   BUT UNDERSTAND
THE BEST PRACTICES TO HELP CLIENTS (I.E
MOBILE DEVELOPERS , FRONT END)
HTTP REQUEST STRUCTURE
FAKING THE USER AGENT VIA PHP
REMEMBER :
$_SERVER[“HTTP_USER_AGENT”]
RESPONSE STRUCTURE
I) HTTP VERBS
HTTP Verb: the action counterpart to the
noun-based resource. The primary or most-
commonly-used HTTP verbs (or methods, as
they are properly called) are POST, GET, PUT,
PATCH, and DELETE.
GET /addresses.php?id=1
Retrieve the address which number is 1
POST : causes changes in the server
(most cases in create, so it shouldn’t be
repeated, it has a body $_POST
POST /addresses.php
Create new address with the data stored
in the post body
Are there other HTTP verbs ???
 PUT : The PUT method replaces all current representations of the target resource with the
request payload..
 Access PUT using PHP
 $_PUT= json_decode(file_get_contents("php://input"),true);
Delete /addresses.php?id=1
update the address which number is 1 with current payload
 $_SERVER[“REQUEST_METHOD”] : gives which verb was used GET OR POST,
Delete
 Delete : Request that a resource be removed; however, the resource
does not have to be removed immediately. It could be an
asynchronous or long-running request.
Delete /addresses.php?id=1
delete the address which number is 1
 $_SERVER[“REQUEST_METHOD”] : gives which verb was
used GET OR POST, Delete
HOW WE GET THE $VERB ?
HTTP STATUS CODES
 2xx (Successful): The request was
successfully received, understood, and
accepted (200)
 201 Created successfully
 202 Deleted successfully
 204 Updated successfully
 200 request fulfilled
 3xx (Redirection): Further action needs to be
taken in order to complete the request (301)
 Setting a response code
http_response_code(500)
 4xx (Client Error): The request contains bad
syntax or cannot be fulfilled (403 & 404)
 403 No access right Forbidden
 404 resource not found
 405 method not found
 402 payment required
 401 bad authentication
 400 bad request
 406 resource not accesptable
 5xx (Server Error): The server failed to fulfill
an apparently valid request (500)
 500 internal server error
REST 101
 REPRESENTATIONAL STATE TRANSFER
(transferring representation of resources)
 SET OF PRINCIPALES ON HOW DATA
COULD BE TRANSFER ELEGANTLY VIA
HTTP
 Each resource has at least one URL
 The focus of a RESTful service is on
resources and how to provide access to
these resources.
 A resource can easily be thought of as an
object as in OOP. A resource can consist
of other resources. While designing a
system, the first thing to do is identify
the resources and determine how they
are related to each other. This is similar
to the first step of designing a database:
Identify entities and relations.
 A RESTful service uses a directory
hierarchy like human readable URIs to
address its resources
 http://MyService/Persons/1
 This URL has following format:
Protocol://ServiceName/ResourceType/R
esourceID
 REST SET OF PRETY URLs
REST 101
 Avoid verbs for your resource unless the resource is a process such as search
 DON’T USE : http://MyService/DeletePerson/1. For Delete a person
 RESTful systems should have a uniform interface. HTTP 1.1 provides a set of HTTP Verbs
(GET, POST, DELETE and PUT)
Examples
: Delete http://MyService/Persons/1
Get: http://MyService/Persons/1
Update: http://MyService/Persons/1
POST http://MyService/Persons/
You should use these methods only for the purpose for which they are intended.
For instance, never use GET to create or delete a resource on the server.
 Use plural nouns for naming your resources.
 Avoid using spaces
http://MyService/Persons?id=1
OR http://MyService/Persons/1
The query parameter approach works just fine and REST does not stop you from using
query parameters. However, this approach has a few disadvantages.
Increased complexity and reduced readability, which will increase if you have more
parameters
Use http://localhost/rest01.php/items/10
Not http://localhost/rest01.php?Resources=items&&id=10
$url_piecies = explode("/",$_SERVER["REQUEST_URI"]);
$resource = (isset($url_piecies[2]))? $url_piecies[2] : "" ;
$resource_id =(isset($url_piecies[3]) && is_numeric($url_piecies[3]) ) ?$url_piecies[3] : 0;
EXAMPLE OF A REST SERVICE
Resource Methods URI Description
Person GET,POST,PUT,
DELETE
http://MyService/Persons/{PersonID}Contains information about a person, can
create new person, update and delete
persons.
{PersonID} is optional
Format: text/JSON
Club GET,POST,PUT http://MyService/Clubs/{ClubID} Contains information about a club.
can create new club & update existing
clubs.
{ClubID} is optional
Format: text/JSON
Search GET http://MyService/Search? Search a person or a club
Format: text/xml
Query Parameters:
Name: String, Name of a person or a club
Country: String, optional, Name of the
country of a person or a club
REST SERVICE STEPS
 Receiving the request & identifying it’s parameters ( VERB, RESOURCE, RESOURCE ID,
PARAMETERS)
 Logging the request (why?)
 Validating the request
 If not valid request , send appropriate code and message
 If valid request , start dispatching (initialize data access and business logic objects which will
handle the request)
 Prepare the response based on the verb (Handler for GET, POST, PUT and DELETE)
 If you have a valid response send it with appropriate response after logging it, why?
 If you don’t have a valid response response is not of valid, send response code and error after
logging it
 Try drawing a flow chart for it
FINALLY CODE
CREARTING A RESTFUL API USING PHP
REMEMBER BEFORE SEE THE WHOLE
THING THAT
$method = $_SERVER['REQUEST_METHOD’];
Use http://localhost/rest01.php/items/10
Not http://localhost/rest01.php?Resources=items&&id=10
$url_piecies = explode("/",$_SERVER["REQUEST_URI"]);
$resource = (isset($url_piecies[2]))? $url_piecies[2] : "" ;
$resource_id =(isset($url_piecies[3]) && is_numeric($url_piecies[3]) ) ?$url_piecies[3] : 0;
header (“Content-Type: application/json”);
$input = json_decode(file_get_contents('php://input'),true);
http_response_code(404)
QUIZ
1) A status code for an http method
not supported
a. 404
b. 400
c. 405
d. 204
 2) If the error is because the
database connection failed, the
response code should be like
a. 5xx
b. 2xx
c. 4xx
d. 3xx
QUIZ
3- When you connect ASYNC-
------ is returned
a. promises
b. Handler
c. Endpoint
d. SDK
4- When you use curl_init() ---
-------- is returned
a. Promise
b. Handler
c. Endpoint
d. SDK
 5- Using Guzzle you can
a. Connect to multiple webservices
concurrently
b. Connect to a webservice
Asynchrounsoly
c. Send GET, POST or any other
HTTP requests
d. All the above
6- if parameter validation failes
because the user sends wrong email
address formats then appropriate
response code is
A. 403
B. 404
C. 400
D. 401
7) HTTP Method that is Read
Only
 GET
 GET & DELETE
 PUT
 POST
8) HTTP Method that if
repeated can create many
new resources
 PUT
 POST
 GET
 DELETE
9) REST has
a. Representational URLS
b. A single endpoint
c. Only JSON formats for communications
d. HTTP and other protocols such as SMTP
10) Attributes of a RESTFUL Request includes all
these except
a. Requested Resource
b. Request Method
c. Status code
d. Request Header
e. Resource ID
f. Parameters
g. Body
11) There are 5 issues in the following code, what are
they ?
12) There are 3 enhancement issues in the
following code what are they ?
13) There are 2 errors in the following code
14) There are 5 errors in the following code
15) The http://php are used to access
a. Request
b. Response
c. Raw Body of the request
d. Raw Body of the response

More Related Content

What's hot

Introduction to REST - API
Introduction to REST - APIIntroduction to REST - API
Introduction to REST - API
Chetan Gadodia
 
ReST (Representational State Transfer) Explained
ReST (Representational State Transfer) ExplainedReST (Representational State Transfer) Explained
ReST (Representational State Transfer) Explained
Dhananjay Nene
 
Api testing bible using postman
Api testing bible using postmanApi testing bible using postman
Api testing bible using postman
Abhishek Saxena
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
Aniruddh Bhilvare
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
Jeetendra singh
 
Soap web service
Soap web serviceSoap web service
Soap web service
NITT, KAMK
 
Express JS
Express JSExpress JS
Express JS
Alok Guha
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
Best practices for RESTful web service design
Best practices for RESTful web service designBest practices for RESTful web service design
Best practices for RESTful web service design
Ramin Orujov
 
Restful Web Services
Restful Web ServicesRestful Web Services
Restful Web Services
Angelin R
 
introduction about REST API
introduction about REST APIintroduction about REST API
introduction about REST API
AmilaSilva13
 
[네이버오픈소스세미나] Contribution, 전쟁의 서막 : Apache OpenWhisk 성능 개선 - 김동경
[네이버오픈소스세미나] Contribution, 전쟁의 서막 : Apache OpenWhisk 성능 개선 - 김동경[네이버오픈소스세미나] Contribution, 전쟁의 서막 : Apache OpenWhisk 성능 개선 - 김동경
[네이버오픈소스세미나] Contribution, 전쟁의 서막 : Apache OpenWhisk 성능 개선 - 김동경
NAVER Engineering
 
Joomla REST API
Joomla REST APIJoomla REST API
Joomla REST API
Ashwin Date
 
Restful api
Restful apiRestful api
Restful api
Anurag Srivastava
 
Exposer des services web SOAP et REST avec symfony 1.4 et Zend Framework
Exposer des services web SOAP et REST avec symfony 1.4 et Zend FrameworkExposer des services web SOAP et REST avec symfony 1.4 et Zend Framework
Exposer des services web SOAP et REST avec symfony 1.4 et Zend FrameworkHugo Hamon
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
Edureka!
 
Rest web services
Rest web servicesRest web services
Rest web services
Paulo Gandra de Sousa
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
NexThoughts Technologies
 

What's hot (20)

Introduction to REST - API
Introduction to REST - APIIntroduction to REST - API
Introduction to REST - API
 
ReST (Representational State Transfer) Explained
ReST (Representational State Transfer) ExplainedReST (Representational State Transfer) Explained
ReST (Representational State Transfer) Explained
 
Api testing bible using postman
Api testing bible using postmanApi testing bible using postman
Api testing bible using postman
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Soap web service
Soap web serviceSoap web service
Soap web service
 
Express JS
Express JSExpress JS
Express JS
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Best practices for RESTful web service design
Best practices for RESTful web service designBest practices for RESTful web service design
Best practices for RESTful web service design
 
Restful Web Services
Restful Web ServicesRestful Web Services
Restful Web Services
 
introduction about REST API
introduction about REST APIintroduction about REST API
introduction about REST API
 
[네이버오픈소스세미나] Contribution, 전쟁의 서막 : Apache OpenWhisk 성능 개선 - 김동경
[네이버오픈소스세미나] Contribution, 전쟁의 서막 : Apache OpenWhisk 성능 개선 - 김동경[네이버오픈소스세미나] Contribution, 전쟁의 서막 : Apache OpenWhisk 성능 개선 - 김동경
[네이버오픈소스세미나] Contribution, 전쟁의 서막 : Apache OpenWhisk 성능 개선 - 김동경
 
Soap vs rest
Soap vs restSoap vs rest
Soap vs rest
 
Soap Vs Rest
Soap Vs RestSoap Vs Rest
Soap Vs Rest
 
Joomla REST API
Joomla REST APIJoomla REST API
Joomla REST API
 
Restful api
Restful apiRestful api
Restful api
 
Exposer des services web SOAP et REST avec symfony 1.4 et Zend Framework
Exposer des services web SOAP et REST avec symfony 1.4 et Zend FrameworkExposer des services web SOAP et REST avec symfony 1.4 et Zend Framework
Exposer des services web SOAP et REST avec symfony 1.4 et Zend Framework
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
 
Rest web services
Rest web servicesRest web services
Rest web services
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 

Similar to Day02 a pi.

Workshop Laravel 5.2
Workshop Laravel 5.2Workshop Laravel 5.2
Workshop Laravel 5.2
Wahyu Rismawan
 
WebApp #3 : API
WebApp #3 : APIWebApp #3 : API
WebApp #3 : API
Jean Michel
 
Getting to know Laravel 5
Getting to know Laravel 5Getting to know Laravel 5
Getting to know Laravel 5
Bukhori Aqid
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
Sudip Simkhada
 
Php intro
Php introPhp intro
Php intro
Jennie Gajjar
 
Php interview-questions and answers
Php interview-questions and answersPhp interview-questions and answers
Php interview-questions and answers
sheibansari
 
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
Evan Mullins
 
Super simple introduction to REST-APIs (2nd version)
Super simple introduction to REST-APIs (2nd version)Super simple introduction to REST-APIs (2nd version)
Super simple introduction to REST-APIs (2nd version)
Patrick Savalle
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
Lorna Mitchell
 
CS1520 Session 2 - Simple Router
CS1520 Session 2 - Simple RouterCS1520 Session 2 - Simple Router
CS1520 Session 2 - Simple Router
Salim Malakouti
 
nguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicenguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicehazzaz
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
Lorna Mitchell
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
Roohul Amin
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
07.pallav
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
RESTful Web Development with CakePHP
RESTful Web Development with CakePHPRESTful Web Development with CakePHP
RESTful Web Development with CakePHP
Andru Weir
 

Similar to Day02 a pi. (20)

Workshop Laravel 5.2
Workshop Laravel 5.2Workshop Laravel 5.2
Workshop Laravel 5.2
 
WebApp #3 : API
WebApp #3 : APIWebApp #3 : API
WebApp #3 : API
 
Getting to know Laravel 5
Getting to know Laravel 5Getting to know Laravel 5
Getting to know Laravel 5
 
Cqrs api v2
Cqrs api v2Cqrs api v2
Cqrs api v2
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
Php intro
Php introPhp intro
Php intro
 
Php intro
Php introPhp intro
Php intro
 
Php intro
Php introPhp intro
Php intro
 
Php interview-questions and answers
Php interview-questions and answersPhp interview-questions and answers
Php interview-questions and answers
 
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
 
Super simple introduction to REST-APIs (2nd version)
Super simple introduction to REST-APIs (2nd version)Super simple introduction to REST-APIs (2nd version)
Super simple introduction to REST-APIs (2nd version)
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
CS1520 Session 2 - Simple Router
CS1520 Session 2 - Simple RouterCS1520 Session 2 - Simple Router
CS1520 Session 2 - Simple Router
 
nguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicenguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-service
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHP
 
RESTful Web Development with CakePHP
RESTful Web Development with CakePHPRESTful Web Development with CakePHP
RESTful Web Development with CakePHP
 

More from ABDEL RAHMAN KARIM

Date Analysis .pdf
Date Analysis .pdfDate Analysis .pdf
Date Analysis .pdf
ABDEL RAHMAN KARIM
 
Agile Course
Agile CourseAgile Course
Agile Course
ABDEL RAHMAN KARIM
 
Agile course Part 1
Agile course Part 1Agile course Part 1
Agile course Part 1
ABDEL RAHMAN KARIM
 
Software as a service
Software as a serviceSoftware as a service
Software as a service
ABDEL RAHMAN KARIM
 
Day03 api
Day03   apiDay03   api
Search engine optimization
Search engine optimization Search engine optimization
Search engine optimization
ABDEL RAHMAN KARIM
 
Seo lec 3
Seo lec 3Seo lec 3
Seo lec 2
Seo lec 2Seo lec 2
Tdd for php
Tdd for phpTdd for php
Tdd for php
ABDEL RAHMAN KARIM
 
OverView to PMP
OverView to PMPOverView to PMP
OverView to PMP
ABDEL RAHMAN KARIM
 
Security fundamentals
Security fundamentals Security fundamentals
Security fundamentals
ABDEL RAHMAN KARIM
 
Over view of software artitecture
Over view of software artitectureOver view of software artitecture
Over view of software artitecture
ABDEL RAHMAN KARIM
 
تلخيص مختصر لكتاب التوحيد و التوكل للامام الغزالى من سلسلة احياء علوم الدين
تلخيص مختصر لكتاب التوحيد و التوكل للامام الغزالى من سلسلة احياء علوم الدينتلخيص مختصر لكتاب التوحيد و التوكل للامام الغزالى من سلسلة احياء علوم الدين
تلخيص مختصر لكتاب التوحيد و التوكل للامام الغزالى من سلسلة احياء علوم الدين
ABDEL RAHMAN KARIM
 

More from ABDEL RAHMAN KARIM (13)

Date Analysis .pdf
Date Analysis .pdfDate Analysis .pdf
Date Analysis .pdf
 
Agile Course
Agile CourseAgile Course
Agile Course
 
Agile course Part 1
Agile course Part 1Agile course Part 1
Agile course Part 1
 
Software as a service
Software as a serviceSoftware as a service
Software as a service
 
Day03 api
Day03   apiDay03   api
Day03 api
 
Search engine optimization
Search engine optimization Search engine optimization
Search engine optimization
 
Seo lec 3
Seo lec 3Seo lec 3
Seo lec 3
 
Seo lec 2
Seo lec 2Seo lec 2
Seo lec 2
 
Tdd for php
Tdd for phpTdd for php
Tdd for php
 
OverView to PMP
OverView to PMPOverView to PMP
OverView to PMP
 
Security fundamentals
Security fundamentals Security fundamentals
Security fundamentals
 
Over view of software artitecture
Over view of software artitectureOver view of software artitecture
Over view of software artitecture
 
تلخيص مختصر لكتاب التوحيد و التوكل للامام الغزالى من سلسلة احياء علوم الدين
تلخيص مختصر لكتاب التوحيد و التوكل للامام الغزالى من سلسلة احياء علوم الدينتلخيص مختصر لكتاب التوحيد و التوكل للامام الغزالى من سلسلة احياء علوم الدين
تلخيص مختصر لكتاب التوحيد و التوكل للامام الغزالى من سلسلة احياء علوم الدين
 

Recently uploaded

Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Marketing internship report file for MBA
Marketing internship report file for MBAMarketing internship report file for MBA
Marketing internship report file for MBA
gb193092
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
Kartik Tiwari
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 

Recently uploaded (20)

Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Marketing internship report file for MBA
Marketing internship report file for MBAMarketing internship report file for MBA
Marketing internship report file for MBA
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 

Day02 a pi.

  • 1. CONTINUE PART 2 : USING REMOTE APIS
  • 3. WHAT IS GUZZLE ? Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. Secondly, Guzzle provides a very clean API to work with. Documentation is very important when working with a library.Guzzle has done a very good job by providing a comprehensive documentation
  • 4. INSTALLING GUZZLE USING COMPOSER Wait a minute what is composer ????
  • 5. OVERVIEW OF COMPOSER ● It's a dependancy manager tool it is used everywhere in the PHP World. All large and well-known website components in other ward it will help you do the following : ● 1- Install 3rd party php tools and framewords ● 2- Update version of the tools you use ● 3- Auto load your own code (so in the future you will only use composer‘s autoloader!!! Cool ? ● ● Composer has two separate elements : ✔ The first is Composer itself which is a command line tool for grabbing and installing what you want to install. ✔ The second is Packagist - the main composer repository. This is where the packages you may want to use are stored. ✔ Every thing Composer installs does that in a directory names vendor which shouldn‘t has any of your code
  • 6. WORKING WITH COMPOSER  Working with composer will has only 3 task types :  1- Define what you want to install (frame work or tool) in json format file  2- Define where your classes files and configuration file or in the future name spaces which you want to load in json file  3- Some command files to make composer run the settings you define  4- Require the autoloader of composer in your code
  • 7. WORK SEQUENCE 1 •First Step •Prepare composer.JSON File to tell composer what you want to install 2 •Second Step •Prepare composer.json file about your autoload options 3 •Third step •Run composer install command
  • 8. 1 & 2 COMPOSER.JSON FILE PREPARATION The Composer.JSON has two sections :  Require : The tools that you want Composer to install  Autoload : where are your classes and configuration files for composer to load , in the future that will be using name space not classmap.
  • 9. COMMAND LINE  Composer selfupdate  Composer install  Composer dump-autoload  Note :  When call composer install composer will add some files and a directory with name vendor in which all 3rd party tools are
  • 11. IN THE CODE Require auto uploader
  • 12. SAME WEATER EXAMPLE USING GUZZLE
  • 13. USING GUZZLE YOU CAN DO ASYNC AND CONCURRENT REQUESTS <<ADVANCED BEGIN>>
  • 15. CALL AN API ASYNCH
  • 16. CONCURRENT REQUESTS TO MULTIPLE APIS
  • 17. USING GUZZLE YOU CAN DO ASYNC AND CONCURRENT REQUESTS FINISHED <<ADVANCED FINISHED>>
  • 18. PART 3 : REST APIS REST has become the default for most Web and mobile apps, 70% of public API are RESTFUL
  • 19. CONCEPTS >> BIG PICTURE >> CODE CODE IS SO EASY   BUT UNDERSTAND THE BEST PRACTICES TO HELP CLIENTS (I.E MOBILE DEVELOPERS , FRONT END)
  • 21. FAKING THE USER AGENT VIA PHP REMEMBER : $_SERVER[“HTTP_USER_AGENT”]
  • 23. I) HTTP VERBS HTTP Verb: the action counterpart to the noun-based resource. The primary or most- commonly-used HTTP verbs (or methods, as they are properly called) are POST, GET, PUT, PATCH, and DELETE.
  • 24. GET /addresses.php?id=1 Retrieve the address which number is 1 POST : causes changes in the server (most cases in create, so it shouldn’t be repeated, it has a body $_POST POST /addresses.php Create new address with the data stored in the post body Are there other HTTP verbs ???
  • 25.  PUT : The PUT method replaces all current representations of the target resource with the request payload..  Access PUT using PHP  $_PUT= json_decode(file_get_contents("php://input"),true); Delete /addresses.php?id=1 update the address which number is 1 with current payload  $_SERVER[“REQUEST_METHOD”] : gives which verb was used GET OR POST, Delete
  • 26.  Delete : Request that a resource be removed; however, the resource does not have to be removed immediately. It could be an asynchronous or long-running request. Delete /addresses.php?id=1 delete the address which number is 1  $_SERVER[“REQUEST_METHOD”] : gives which verb was used GET OR POST, Delete
  • 27. HOW WE GET THE $VERB ?
  • 28. HTTP STATUS CODES  2xx (Successful): The request was successfully received, understood, and accepted (200)  201 Created successfully  202 Deleted successfully  204 Updated successfully  200 request fulfilled  3xx (Redirection): Further action needs to be taken in order to complete the request (301)  Setting a response code http_response_code(500)  4xx (Client Error): The request contains bad syntax or cannot be fulfilled (403 & 404)  403 No access right Forbidden  404 resource not found  405 method not found  402 payment required  401 bad authentication  400 bad request  406 resource not accesptable  5xx (Server Error): The server failed to fulfill an apparently valid request (500)  500 internal server error
  • 29. REST 101  REPRESENTATIONAL STATE TRANSFER (transferring representation of resources)  SET OF PRINCIPALES ON HOW DATA COULD BE TRANSFER ELEGANTLY VIA HTTP  Each resource has at least one URL  The focus of a RESTful service is on resources and how to provide access to these resources.  A resource can easily be thought of as an object as in OOP. A resource can consist of other resources. While designing a system, the first thing to do is identify the resources and determine how they are related to each other. This is similar to the first step of designing a database: Identify entities and relations.  A RESTful service uses a directory hierarchy like human readable URIs to address its resources  http://MyService/Persons/1  This URL has following format: Protocol://ServiceName/ResourceType/R esourceID  REST SET OF PRETY URLs
  • 30. REST 101  Avoid verbs for your resource unless the resource is a process such as search  DON’T USE : http://MyService/DeletePerson/1. For Delete a person  RESTful systems should have a uniform interface. HTTP 1.1 provides a set of HTTP Verbs (GET, POST, DELETE and PUT) Examples : Delete http://MyService/Persons/1 Get: http://MyService/Persons/1 Update: http://MyService/Persons/1 POST http://MyService/Persons/ You should use these methods only for the purpose for which they are intended. For instance, never use GET to create or delete a resource on the server.  Use plural nouns for naming your resources.  Avoid using spaces
  • 31. http://MyService/Persons?id=1 OR http://MyService/Persons/1 The query parameter approach works just fine and REST does not stop you from using query parameters. However, this approach has a few disadvantages. Increased complexity and reduced readability, which will increase if you have more parameters Use http://localhost/rest01.php/items/10 Not http://localhost/rest01.php?Resources=items&&id=10 $url_piecies = explode("/",$_SERVER["REQUEST_URI"]); $resource = (isset($url_piecies[2]))? $url_piecies[2] : "" ; $resource_id =(isset($url_piecies[3]) && is_numeric($url_piecies[3]) ) ?$url_piecies[3] : 0;
  • 32. EXAMPLE OF A REST SERVICE Resource Methods URI Description Person GET,POST,PUT, DELETE http://MyService/Persons/{PersonID}Contains information about a person, can create new person, update and delete persons. {PersonID} is optional Format: text/JSON Club GET,POST,PUT http://MyService/Clubs/{ClubID} Contains information about a club. can create new club & update existing clubs. {ClubID} is optional Format: text/JSON Search GET http://MyService/Search? Search a person or a club Format: text/xml Query Parameters: Name: String, Name of a person or a club Country: String, optional, Name of the country of a person or a club
  • 33. REST SERVICE STEPS  Receiving the request & identifying it’s parameters ( VERB, RESOURCE, RESOURCE ID, PARAMETERS)  Logging the request (why?)  Validating the request  If not valid request , send appropriate code and message  If valid request , start dispatching (initialize data access and business logic objects which will handle the request)  Prepare the response based on the verb (Handler for GET, POST, PUT and DELETE)  If you have a valid response send it with appropriate response after logging it, why?  If you don’t have a valid response response is not of valid, send response code and error after logging it  Try drawing a flow chart for it
  • 34. FINALLY CODE CREARTING A RESTFUL API USING PHP
  • 35. REMEMBER BEFORE SEE THE WHOLE THING THAT $method = $_SERVER['REQUEST_METHOD’]; Use http://localhost/rest01.php/items/10 Not http://localhost/rest01.php?Resources=items&&id=10 $url_piecies = explode("/",$_SERVER["REQUEST_URI"]); $resource = (isset($url_piecies[2]))? $url_piecies[2] : "" ; $resource_id =(isset($url_piecies[3]) && is_numeric($url_piecies[3]) ) ?$url_piecies[3] : 0; header (“Content-Type: application/json”); $input = json_decode(file_get_contents('php://input'),true); http_response_code(404)
  • 36. QUIZ 1) A status code for an http method not supported a. 404 b. 400 c. 405 d. 204  2) If the error is because the database connection failed, the response code should be like a. 5xx b. 2xx c. 4xx d. 3xx
  • 37. QUIZ 3- When you connect ASYNC- ------ is returned a. promises b. Handler c. Endpoint d. SDK 4- When you use curl_init() --- -------- is returned a. Promise b. Handler c. Endpoint d. SDK
  • 38.  5- Using Guzzle you can a. Connect to multiple webservices concurrently b. Connect to a webservice Asynchrounsoly c. Send GET, POST or any other HTTP requests d. All the above 6- if parameter validation failes because the user sends wrong email address formats then appropriate response code is A. 403 B. 404 C. 400 D. 401
  • 39. 7) HTTP Method that is Read Only  GET  GET & DELETE  PUT  POST 8) HTTP Method that if repeated can create many new resources  PUT  POST  GET  DELETE
  • 40. 9) REST has a. Representational URLS b. A single endpoint c. Only JSON formats for communications d. HTTP and other protocols such as SMTP 10) Attributes of a RESTFUL Request includes all these except a. Requested Resource b. Request Method c. Status code d. Request Header e. Resource ID f. Parameters g. Body
  • 41. 11) There are 5 issues in the following code, what are they ?
  • 42. 12) There are 3 enhancement issues in the following code what are they ?
  • 43. 13) There are 2 errors in the following code
  • 44. 14) There are 5 errors in the following code
  • 45. 15) The http://php are used to access a. Request b. Response c. Raw Body of the request d. Raw Body of the response