SlideShare ist ein Scribd-Unternehmen 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

Weitere ähnliche Inhalte

Was ist angesagt?

Sending emails through PHP
Sending emails through PHPSending emails through PHP
Sending emails through PHP
krishnapriya Tadepalli
 
php
phpphp
HTTP Basics
HTTP BasicsHTTP Basics
HTTP Basics
sanjoysanyal
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
Manish Bothra
 
Asp.net and .Net Framework ppt presentation
Asp.net and .Net Framework ppt presentationAsp.net and .Net Framework ppt presentation
Asp.net and .Net Framework ppt presentation
abhishek singh
 
PHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniterPHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniter
KHALID C
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and response
Sahil Agarwal
 
Http Introduction
Http IntroductionHttp Introduction
Http Introduction
Akshay Dhole
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
priya Nithya
 
Introduction To CodeIgniter
Introduction To CodeIgniterIntroduction To CodeIgniter
Introduction To CodeIgniter
schwebbie
 
Loops PHP 04
Loops PHP 04Loops PHP 04
Loops PHP 04
Spy Seat
 
Php
PhpPhp
Building Advanced XSS Vectors
Building Advanced XSS VectorsBuilding Advanced XSS Vectors
Building Advanced XSS Vectors
Rodolfo Assis (Brute)
 
Javascript
JavascriptJavascript
Javascript
mussawir20
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
Ismail Mukiibi
 
Http request and http response
Http request and http responseHttp request and http response
Http request and http response
Nuha Noor
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
sentayehu
 
Api presentation
Api presentationApi presentation
Api presentation
Tiago Cardoso
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
Patrick Savalle
 
Introduction To PHP
Introduction To PHPIntroduction To PHP
Introduction To PHP
Shweta A
 

Was ist angesagt? (20)

Sending emails through PHP
Sending emails through PHPSending emails through PHP
Sending emails through PHP
 
php
phpphp
php
 
HTTP Basics
HTTP BasicsHTTP Basics
HTTP Basics
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 
Asp.net and .Net Framework ppt presentation
Asp.net and .Net Framework ppt presentationAsp.net and .Net Framework ppt presentation
Asp.net and .Net Framework ppt presentation
 
PHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniterPHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniter
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and response
 
Http Introduction
Http IntroductionHttp Introduction
Http Introduction
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
 
Introduction To CodeIgniter
Introduction To CodeIgniterIntroduction To CodeIgniter
Introduction To CodeIgniter
 
Loops PHP 04
Loops PHP 04Loops PHP 04
Loops PHP 04
 
Php
PhpPhp
Php
 
Building Advanced XSS Vectors
Building Advanced XSS VectorsBuilding Advanced XSS Vectors
Building Advanced XSS Vectors
 
Javascript
JavascriptJavascript
Javascript
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
Http request and http response
Http request and http responseHttp request and http response
Http request and http response
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
 
Api presentation
Api presentationApi presentation
Api presentation
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
 
Introduction To PHP
Introduction To PHPIntroduction To PHP
Introduction To PHP
 

Ähnlich wie 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
 
Cqrs api v2
Cqrs api v2Cqrs api v2
Cqrs api v2
Brandon Mueller
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
Sudip Simkhada
 
Php intro
Php introPhp intro
Php intro
Jennie Gajjar
 
Php intro
Php introPhp intro
Php intro
Jennie Gajjar
 
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-service
hazzaz
 
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
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHP
Matthew Turland
 
RESTful Web Development with CakePHP
RESTful Web Development with CakePHPRESTful Web Development with CakePHP
RESTful Web Development with CakePHP
Andru Weir
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 
تلخيص مختصر لكتاب التوحيد و التوكل للامام الغزالى من سلسلة احياء علوم الدين
تلخيص مختصر لكتاب التوحيد و التوكل للامام الغزالى من سلسلة احياء علوم الدينتلخيص مختصر لكتاب التوحيد و التوكل للامام الغزالى من سلسلة احياء علوم الدين
تلخيص مختصر لكتاب التوحيد و التوكل للامام الغزالى من سلسلة احياء علوم الدين
 

Kürzlich hochgeladen

South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
S. Raj Kumar
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
imrankhan141184
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
Wahiba Chair Training & Consulting
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 

Kürzlich hochgeladen (20)

South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 

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