Instant Download Building RESTful Web Services With PHP 7 Ahmad PDF All Chapter
Instant Download Building RESTful Web Services With PHP 7 Ahmad PDF All Chapter
com
https://textbookfull.com/product/building-restful-
web-services-with-php-7-ahmad/
https://textbookfull.com/product/integrating-web-services-with-oauth-
and-php-a-php-architect-guide-1st-edition-matthew-frost/
textbookfull.com
https://textbookfull.com/product/classroom-assessment-what-teachers-
need-to-know-10th-edition-w-james-popham/
textbookfull.com
Aligning Perspectives in Gender Mainstreaming: Gender,
Health, Safety, and Wellbeing Juliet Hassard
https://textbookfull.com/product/aligning-perspectives-in-gender-
mainstreaming-gender-health-safety-and-wellbeing-juliet-hassard/
textbookfull.com
https://textbookfull.com/product/1984-and-philosophy-is-resistance-
futile-ezio-di-nucci/
textbookfull.com
https://textbookfull.com/product/fire-fundamentals-and-control-first-
edition-haessler/
textbookfull.com
https://textbookfull.com/product/translational-bioinformatics-and-
systems-biology-methods-for-personalized-medicine-qing-yan-auth/
textbookfull.com
Jews, Cinema and Public Life in Interwar Britain Gil
Toffell
https://textbookfull.com/product/jews-cinema-and-public-life-in-
interwar-britain-gil-toffell/
textbookfull.com
Building RESTful Web Services with PHP 7
BIRMINGHAM - MUMBAI
Building RESTful Web Services
with PHP 7
Every effort has been made in the preparation of this book to ensure the
accuracy of the information presented. However, the information contained
in this book is sold without warranty, either express or implied. Neither the
author, nor Packt Publishing, and its dealers and distributors will be held
liable for any damages caused or alleged to be caused directly or indirectly
by this book.
ISBN 978-1-78712-774-6
www.packtpub.com
Credits
I would like to thank my family for making my life easy and full of
happiness.
www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktP
ub.com.
Did you know that Packt offers eBook versions of every book published,
with PDF and ePub files available? You can upgrade to the eBook version
at www.PacktPub.com and as a print book customer, you are entitled to a
discount on the eBook copy. Get in touch with us at [email protected] for
more details.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full
access to all Packt books and video courses, as well as industry-leading
tools to help you plan your personal development and advance your career.
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Customer Feedback
Thanks for purchasing this Packt book. At Packt, quality is at the heart of
our editorial process. To help us improve, please leave us an honest review
on this book's Amazon page at https://www.amazon.com/dp/B075CK8S7D.
If you'd like to join our team of regular reviewers, you can e-mail us at
[email protected]. We award our regular reviewers with free
eBooks and videos in exchange for their valuable feedback. Help us be
relentless in improving our products!
Table of Contents
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Downloading the example code
Errata
Piracy
Questions
1. RESTful Web Services, Introduction and Motivation
Web services
Why a web service?
REST architecture
Client server
Stateless
Cache-able
Uniform interface
Resource identification
Manipulation of resources through representations
Self-descriptive messages
Hypermedia as the engine of application state (HATEOAS)
Code on demand (optional)
Layered system
RESTful web services
Conventions of RESTful web services
HTTP verbs and URL structure
List operation
Create operation
READ operation
Update operation
Delete operation
Why RESTful web services?
REST versus SOAP
Nature of HTTP methods
Safe/unsafe HTTP methods
Idempotent and non-idempotent methods
HTTP response
Response type
Response codes
Case study - RESTful web service endpoints for a blog
Blog post
Requirements
Endpoints
Creating blog post
Reading blog post
Updating blog post
Delete blog post
Listing all blog posts
Blog post comments
Requirements
Endpoints
Creating the post's comment
Reading a comment
Updating a comment
Deleting a post comment
Listing all comments for a particular post
More resources
Summary
2. PHP7, To Code It Better
Scalar type declaration
Return type declaration
Null coalescing operator
Spaceship operator
Group use declarations
Generator-related features
What are generators?
Generator return expression
Generator delegation
Anonymous classes
Closure::call()
Errors and exceptions
PHP7.1
Nullable types
Symmetric array destructuring
Support for keys in list()
Multi-catch exception handling
More resources
Summary
3. Creating RESTful Endpoints
Creating a REST API for a blog in PHP
Creating a database schema
Blog user/author table schema
SQL for users table
Blog post table schema
Blog post comments schema
Creating a RESTful API's endpoint
Code structure
Common components
DB class
Router class
Code sync
Creating blog post endpoints
REST client
To do
Visible flaws
Validation
Solution
Authentication
Solution
Proper 404 pages
Summary
4. Reviewing Design Flaws and Security Threats
Finding problems in the current code
Structural and design flaws
Missing query builder layer
Incomplete router
Usage of OOP
Separate Configurations from Implementation
Should write tests
Input validation
Handling 404 and other errors
Meta information missing
DB fields abstraction
Security
Securing API endpoints
What is Auth middleware?
Common security threats in RESTful web services
Use of HTTPS
Securing an API key/token
Not passing an access token in the URL
Access token expiration
Limited scope access token
Public and private endpoints
Public API endpoints
Insecure direct object reference
Restricting allowable verbs
Input validation
Available reusable code
Summary
5. Load and Resolve with Composer, an Evolutionary
Introduction to Composer
Installation
Installation on Windows
Installation on Linux/Unix/OS X
Global Installation
Usage of Composer
Composer as a dependency manager
Installing packages
Installing using composer.json
The composer.json in detail
The require object
The require-dev object
The autoload and autoload-dev
The scripts
The composer.lock
Composer as an auto-loader
Example
Composer for creating a project
Example
Summary
6. Illuminating RESTful Web Services with Lumen
Introducing Lumen
Why micro-framework?
Why Lumen?
What Lumen provides
What Lumen has in common with Laravel
How Lumen is different from Laravel
What exactly Lumen provides
A Good Structure
Separate configurations
Router
Middle-wares
Service Container and Dependency Injection
HTTP responses
Validation
Eloquent ORM
Database migration and seeding
Unit testing
Installing Lumen
Configuration
Setting up the database
Writing migrations
Writing RESTful web service endpoints
Writing the first controller
Lumen routes
REST resource
Eloquent ORM (model layer)
Creating models
Eloquent relationships
Controller Implementation
What we are missing?
Validation and negative cases?
/api/posts with GET method
/api/posts with the POST method
/api/posts/1 with the GET method
/api/posts/1 with the PATCH/PUT method
/api/posts/1 with the DELETE method
User authentication
Other missing elements
Comment Resource Implementation
Summary
7. Improving RESTful Web Services
Dingo, simplifying RESTful API development
Installation and configuration
Simplifying routes
API versioning
Rate limiting
Internal requests
Responses
Authentication and middleware
JWT Auth setup
The Manual way
Simpler way through Lumen JWT authentication integration
package
Authentication
Log in
Invalidate token
Refresh token
Transformers
Understanding and setting transformers
Using transformers
Encryption
SSL certificate, different options
Summary
8. API Testing – Guards on the Gates
The need for automated tests
Types of testing
Unit testing
Acceptance testing
Functional testing
Integration testing
What type of testing will we do?
Testing frameworks
CodeCeption introduction
Setup and understanding the structure
tests/{suite-name}/
tests/{suite-name}.suite.yml
tests/_support/_generated/{suite-name}TesterActions.php
tests/_support/{suite-name}Tester.php
tests/_support/Helper/{suite-name}.php
Creating the API suite
Configuring the API suite
Writing test cases
API tests for post resource
Other test cases
Summary
More resources
9. Microservices
Introducing Microservices
How to divide an application into microservices?
Motivation towards microservices
Maintenance and debugging
Scalability
Technology diversity
Resilience
Replaceability
Parallelization
How it is different from SOA
Team structure
Challenges of micro-services
Infrastructure maintenance
Performance
Debugging and fault-finding
Logs should be centralized
Logs should be searchable
Track chain of requests
Dynamic log levels
Implementation
Deployments
Inter-services communication
Synchronous communication
Asynchronous communication
Shared library or common code
Summary
What's next
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Preface
Web services has always been an important topic. With REST, things
became simpler and better. Nowadays, RESTful web services are widely
used. It was important a decade ago, but Single Page Applications (SPAs)
and mobile applications have increased its usage greatly. The aim of this
book is to educate PHP developers about the RESTful web services
architecture, the current tools available to efficiently create RESTful web
services such as a micro-framework named Lumen, automated API testing,
the API testing framework, security and microservices architecture.
In other words, although this book is intended for PHP developers, it will
benefit them beyond just PHP. So, this book is not a cookbook, but a
journey in which you start learning about RESTful webservices and PHP7
and then start building RESTful web services. You can then keep improving
your RESTful web services by learning about the problems in it and fixing
those. During such improvements, you will learn the different things in PHP
and benefit even beyond PHP.
What this book covers
Chapter 1, RESTful Web Services, Introduction and Motivation, introduces
you to web services, REST architecture, the RESTful web services, and its
comparison to other web services such as HTTP verbs and RESTful
endpoints. It also explains web services through the example of a blog and
then talk about the response format and response code.
Anyone who has some basic PHP knowledge and wants to build
RESTful web services.
Developers who know basic PHP and have developed a basic dynamic
website and want to build a RESTful web service.
Developers who have learned PHP and worked mostly in open source
CMS, such as WordPress, and want to move toward developing
custom applications where a web service needs to be built.
Developers who are stuck with legacy systems done in Code Igniter
and want to explore the modern ecosystem of PHP.
Developers who have used modern frameworks such as Yii or Laravel,
but are not sure about the critical pieces required to build the REST
API that not only serves the purpose but works well in the long run,
something that doesn't always need manual testing and is maintainable
and extendable.
Seasoned PHP developers who have created a very basic API that
returns data but want to make themselves familiar with how it should
be done according to REST standards, how it will work when
authentication comes into the picture, and how to write tests for it.
Random documents with unrelated
content Scribd suggests to you:
uusimaan varakreiville sen markiisin arvon, jonka kuningas Jaakko oli
lahjoittanut edelliselle varakreiville. Mutta kun varakreivi suhtautui
kielteisesti tähän lahjuslupaukseen, Holt uhkasi tykkänään kumota,
varakreivin oikeudet Castlewoodin tilukseen ja arvonimeen.
Vahvistaakseen tätä hämmästyttävää tietoa, josta Henry Esmondin
isäntä vasta silloin sai selvän, Holt saapui evästyksenään entisen
lordin Boynen taistelun jälkeen Trimissä, Irlannissa, antama
kuolintunnustus. Tämä tunnustus oli tehty sekä irlantilaiselle papille
että eräälle ranskalaiselle Holtin veljeskuntaan kuuluvalle
kirkonmiehelle, joka toimi kuningas Jaakon sotaväen keskuudessa.
Holt näytti tai oli näyttävinään, todistuksen, että entinen varakreivi
Esmond oli vihitty äitini kanssa Brysselin kaupungissa v. 1677, jolloin
varakreivi, silloinen Thomas Esmond, palveli englantilaisessa
sotaväessä Flanderissa. Holt sanoi, että hän voisi todistaa, että tämä
Gertrude, jonka hänen miehensä kauan sitten oli hyljännyt, vielä eli
ja oli tehnyt nunnanvalan vuonna 1685 Brysselissä; sinä vuonna
Thomas Esmond nai setänsä tyttären, Isabellan, jota nyt sanottiin
Castlewoodin leskivarakreivittäreksi. Ja jättäen varakreivin
kahdeksitoista tunniksi pohtimaan tätä hämmästyttävää uutista (niin
kertoi kuoleva lordiparka) Holt katosi papereineen samalla
ihmeellisellä tavalla kuin oli tullutkin. Esmond tiesi tavan varsin hyvin
— siitä akkunasta, josta oli nähnyt isän poistuvan; mutta sen
selittämisestä lordiparalle ei olisi ollut mitään hyötyä; oli vain
poimittava hänen hyytyviltä huuliltaan sanat, joita hän hetken
kuluttua ei enää kykenisi lausumaan.
Kuka oli hänen äitinsä? Mikä oli ollut tämän nimi? Koska hän oli
kuollut? Esmondilla oli palava halu löytää joku, joka voisi vastata
näihin kysymyksiin, ja hän ajatteli esittää ne tädilleenkin,
varakreivittärelle, joka oli tietämättään omaksunut nimen, johon
Henryn äidillä oli oikeus. Mutta varakreivitär ei tietänyt mitään tai
näki hyväksi olla mitään tietämättä tästä aineesta, eikä mr. Esmond
myöskään voinut häntä paljon ahdistaa siitä puhumaan. Isä Holt oli
ainoa ihminen, joka voi häntä tässä suhteessa valistaa, ja Esmond
tunsi, että hänen täytyi odottaa, kunnes jokin sattuma tai uusi juoni
vei hänet vanhan ystävänsä tulille tai toi tuon uutteran ja
väsymättömän olennon taas takaisin Englantiin.
V luku.
Samalla kuin Esmondin asiat edistyivät näin hyvin, sai hän osansa
myös huvista ja kävi toisten nuorten herrain kanssa kahviloissa,
teattereissa ja Mallissa. Hän paloi halusta saada kuulla rakkaasta
emännästään ja hänen perheestään: monta monituista kertaa hänen
ajatuksensa hellänä kiiti heidän luokseen kaupungin huvien ja ilojen
keskeltä. Ja usein kun hänen seurapiiriinsä kuulavat nuorukaiset
pitivät hauskaa ravintoloissa ja joivat maljoja (niinkuin sen aikuinen
tapa oli) viininsä ääressä, Esmond ajatteli kahta henkilöä — kahta
kaunista naista, joita hän oli tottunut melkein jumaloimaan, ja
tyhjensi lasinsa huokaisten.
Mr. Esmond käski siis, sensijaan että olisi mennyt sinä iltana
päivälliselle "Ruusuun", palvelijansa pakkaamaan matkalaukun ja
hankkimaan hänelle hevoset; ja hän oli jo Farnhamissa, joka on
puolitiessä Walcote'iin mennessä, kolmenkymmenen englannin
penikulman päässä kaupungista, ennenkuin hänen toverinsa vielä
olivat päässeet käsiksi ateriaansa näytelmän jälkeen. Hän kielsi
palvelijaansa ilmoittamasta rouva leskivarakreivittären talossa tästä
retkestä, jolle hän oli lähdössä; ja koska Chelsea oli kaukana
Lontoosta ja tiet olivat huonot ja maantierosvojen vallassa, ja koska
Esmondilla oli usein tapana ollessaan huvittelevien toverien parissa
yöpyä jonkun ystävän asuntoon kaupungissa, ei ollut pelkoa, että
hänen poissaolonsa tekisi hänen vanhan tätinsä levottomaksi. Tuota
vanhaa rouvaa ei tosiaankaan mikään ihastuttanut enemmän kuin
kuvitelma, että mon cousin, tuo parantumaton nuori syntipukki, oli
kaupungilla löylyttämässä vartijaa tai jossain muussa
yltiöpäisyydessä. Silloin kun varakreivitär ei ollut hartauskirjojensa
ääressä, hän piti Etheridgeä ja Sedleyä kelvollisena lukemisena. Hän
tunsi tuhansia koreita juttuja Rochesterista, Harry Jermynistä ja
Hamiltonista; ja jos Esmond vain olisi voinut karata jonkun
kaupunkilaisrouvan kanssa, olen varma, että varakreivitär olisi
pantannut timanttinsa (paras niistä oli annettu Chaillot'n ladyllemme)
maksaakseen Esmondin aikaansaamat vahingot.
"Niin, talo, josta minulla on niin paljon pyhiä muistoja", virkkoi mr.
Tusher (ja Harry muisti miten Tomin isä löylyytti häntä siellä) —
"talo, joka on kunnioitetun isäntäni ja kaikkein korkeasti
kunnioitetuimman emäntäni talon läheisyydessä, on aina oleva rakas
asuinsijani. Mutta rouva, kirkonpalvelija odottaa saadakseen sulkea
portit teidän armonne jälkeen."
"En pyytänyt muuta kuin saada aina olla lähellänne", vastasi mr.
Esmond.
"Mutta parasta oli sinun mennä, Harry. Kun ei maailma voi rauhaa
antaa, niin tiedät, mistä sinun tulee sitä etsiä; mutta sen, jolla on
sinun vahva mielikuvituksesi ja palavat halusi, on koeteltava
maailmaa ensin, ennenkuin hän väsyy siihen. Ei saattanut
ajatellakaan — tai jos niin kerran tehtiin, niin johtui se vain minun
itserakkaudestani — että sinä jäisit maalaisherran kappalaiseksi ja
pienen pojan kasvattajaksi. Sinä serkku, olet Esmondien sukua, joka
nuoruudessa on aina ollut hurjaa. Katsopa Francistä: Hän on vain
viisitoistavuotias ja tuskin saatan pitää häntä pesässä. Hänen
puheensa on pelkkää sotaa ja huvittelemista ja hän toivoo
pääsevänsä seuraavalle sotaretkelle. Varmaankin hän ja nuori lordi
Churchill menevät sinne yhdessä. Lordi Marlborough on ollut hyvä
meille. Sinähän tiedät, miten ystävällisiä he olivat minulle
onnettomuudessani. Ja niin oli myös sinun — sinun isäsi leski.
Kukaan ei tiedä, miten hyvä maailma on, ennenkuin surut
koettelevat meitä. Lady Marlborough'n hyvyyden ansiota on, että
Beatrixilla on paikkansa hovissa ja Frankista pitää huolta prinsessan
kamariherra. Ja leski varakreivitär, isäsi leski, on luvannut avustaa
sinua, eikö totta?"
"Ja nyt alamme lähestyä kotia", jatkoi lady. "Tiesin, että sinä
tulisit, Harry, vaikka — vaikkapa vain antamaan minulle anteeksi että
olin puhunut tylysti tuon kauhean, kauhean onnettomuuden jälkeen.
Silloin, sinut tavatessani, olin puoliksi mielettömänä surusta. Nyt
tiedän — minulle on kerrottu — tuo hylkykin, jonka nimeä en voi
milloinkaan mainita, on niin sanonut: sinä koetit estää riitaa ja
halusit kohdistaa sen itseesi, lapsiparka. Mutta Jumalan tahto oli,
että minua rangaistiin ja että rakas lordini kaatui."
"Tiedän sen, tiedän sen", vastasi lady niin suloisen nöyrästi, että
Esmond alkoi katua, että hän oli ollenkaan tohtinut nuhdella ladyä.
"Minä tiedän, miten paha sydämeni on ollut; ja minäkin olen
kärsinyt, rakkaani. Mitä tunnustin mr. Atterburylle — minun ei tule
kertoa enempää. Hän — minä lupasin, etten kirjoittasi sinulle ja
etten tulisi luoksesi ja parempihan olikin, kun nyt kerran olimme
eronneet, että olimme erossa. Mutta minä tiesin, että sinä tulisit
takaisin, sen myönnän. Eihän se ole kenenkään vika. Ja tänään
Henry, kun virressä laulettiin tuota kohtaa: 'Herra palautti Sionin
vangit, niin me olimme kuin unta näkeväiset' niin minä ajattelin:
juuri niin kuin unta näkeväiset — kuin unta näkeväiset. Ja sitten
jatkui virsi: 'Ne, jotka kyynelin kylvävät, ilolla niittää saavat;
matkansa käyvät itkien ja siemenen kalliin kylvävät. He riemulla
palaavat jälleen ja lyhteensä he tuovat.' minä kohotin katseeni
kirjasta ja näin sinut. En ollut vähääkään hämmästynyt nähdessäni
sinut. Minä tiesin, että sinä tulisit, armaani, ja minä näin auringon
kullan kehystävän päätäsi."