Building RESTful Web Services with PHP 7
()
About this ebook
Learn how to build RESTful API and web services in PHP 7
About This Book
- Leverage the Lumen framework to build RESTful API endpoints for your applications
- Understand how to increase efficiency and security of your web service.
- Learn to apply the concepts by implementing the examples covered in the book
Who This Book Is For
This book is for PHP developers who wish to learn about the REST architecture to be able to build and consume REST APIs in their applications.
What You Will Learn
- Understand the REST API architecture and its benefits
- Write RESTful API web services in PHP 7
- Address security-elated issues in a REST API
- Leverage the importance of automated testing and write tests for API endpoints
- Identify security flaws in our current API endpoints and tackle them effectively
- Observe the working of Lumen microframeworks and write RESTful web services in it
In Detail
REST is the most wide spread and effective standard to develop APIs for internet services. With the way PHP and its eco-system has modernized the way code is written by simplifying various operations, it is useful to develop RESTful APIs with PHP 7 and modern tools.
This book explains in detail how to create your own RESTful API in PHP 7 that can be consumed by other users in your organization.
Starting with a brief introduction to the fundamentals of REST architecture and the new features in PHP 7, you will learn to implement basic RESTful API endpoints using vanilla PHP. The book explains how to identify flaws in security and design and teach you how to tackle them. You will learn about composer, Lumen framework and how to make your RESTful API cleaner, secure and efficient. The book emphasizes on automated tests, teaches about different testing types and give a brief introduction to microservices which is the natural way forward.
After reading this book, you will have a clear understanding of the REST architecture and you can build a web service from scratch.
Style and approach
This book will get you started with REST architecture and will also teach you different methods to build web services from scratch.
Related to Building RESTful Web Services with PHP 7
Related ebooks
Mastering ASP.NET Core 2.0: MVC patterns, configuration, routing, deployment, and more Rating: 0 out of 5 stars0 ratingsPHP 7 Programming Blueprints: Rethink PHP Rating: 0 out of 5 stars0 ratingsProgressive Web Application Development by Example: Develop fast, reliable, and engaging user experiences for the web Rating: 0 out of 5 stars0 ratingsMastering ASP.NET Web API Rating: 0 out of 5 stars0 ratingsBuilding RESTful Web Services with Java EE 8: Create modern RESTful web services with the Java EE 8 API Rating: 0 out of 5 stars0 ratingsLearning PHP 7 High Performance Rating: 0 out of 5 stars0 ratingsWebpack 5 Up and Running: A quick and practical introduction to the JavaScript application bundler Rating: 0 out of 5 stars0 ratingsASP.NET Core 3 and React: Hands-On full stack web development using ASP.NET Core, React, and TypeScript 3 Rating: 0 out of 5 stars0 ratingsBeginning React: Simplify your frontend development workflow and enhance the user experience of your applications with React Rating: 0 out of 5 stars0 ratingsEcho Quick Start Guide: Build lightweight and high-performance web apps with Echo Rating: 0 out of 5 stars0 ratingsHands-On Reactive Programming with Reactor: Build reactive and scalable microservices using the Reactor framework Rating: 0 out of 5 stars0 ratingsMastering C++ Multithreading Rating: 0 out of 5 stars0 ratingsLearning Behavior-driven Development with JavaScript Rating: 5 out of 5 stars5/5Building a RESTful Web Service with Spring Rating: 5 out of 5 stars5/5Distributed Computing in Java 9 Rating: 0 out of 5 stars0 ratingsHands-On High Performance with Spring 5: Techniques for scaling and optimizing Spring and Spring Boot applications Rating: 0 out of 5 stars0 ratingsNext.js Quick Start Guide: Server-side rendering done right Rating: 0 out of 5 stars0 ratingsBuilding RESTful Web services with Go: Learn how to build powerful RESTful APIs with Golang that scale gracefully Rating: 0 out of 5 stars0 ratingsBeginning PHP: Master the latest features of PHP 7 and fully embrace modern PHP development Rating: 0 out of 5 stars0 ratingsSelenium WebDriver Quick Start Guide: Write clear, readable, and reliable tests with Selenium WebDriver 3 Rating: 0 out of 5 stars0 ratings
Internet & Web For You
How to Disappear and Live Off the Grid: A CIA Insider's Guide Rating: 0 out of 5 stars0 ratingsNo Place to Hide: Edward Snowden, the NSA, and the U.S. Surveillance State Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5The Hacker Crackdown: Law and Disorder on the Electronic Frontier Rating: 4 out of 5 stars4/5The Gothic Novel Collection Rating: 5 out of 5 stars5/5How to Be Invisible: Protect Your Home, Your Children, Your Assets, and Your Life Rating: 4 out of 5 stars4/5How To Start A Profitable Authority Blog In Under One Hour Rating: 5 out of 5 stars5/5How To Start A Podcast Rating: 4 out of 5 stars4/5Social Engineering: The Science of Human Hacking Rating: 3 out of 5 stars3/5How To Make Money Blogging: How I Replaced My Day-Job With My Blog and How You Can Start A Blog Today Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Wordpress for Beginners: The Easy Step-by-Step Guide to Creating a Website with WordPress Rating: 5 out of 5 stars5/5An Ultimate Guide to Kali Linux for Beginners Rating: 3 out of 5 stars3/5Blogging For Dummies Rating: 0 out of 5 stars0 ratingsStop Asking Questions: How to Lead High-Impact Interviews and Learn Anything from Anyone Rating: 5 out of 5 stars5/5HTML in 30 Pages Rating: 5 out of 5 stars5/5Tor and the Dark Art of Anonymity Rating: 5 out of 5 stars5/5Cybersecurity All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsLearning Google Apps Script Rating: 4 out of 5 stars4/5Surveillance and Surveillance Detection: A CIA Insider's Guide Rating: 3 out of 5 stars3/5The Digital Marketing Handbook: A Step-By-Step Guide to Creating Websites That Sell Rating: 5 out of 5 stars5/5More Porn - Faster!: 50 Tips & Tools for Faster and More Efficient Porn Browsing Rating: 3 out of 5 stars3/5The Mega Box: The Ultimate Guide to the Best Free Resources on the Internet Rating: 4 out of 5 stars4/5Hacking : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Ethical Hacking Rating: 5 out of 5 stars5/5
Reviews for Building RESTful Web Services with PHP 7
0 ratings0 reviews
Book preview
Building RESTful Web Services with PHP 7 - Haafiz Waheed-ud-din Ahmad
Building RESTful Web Services with PHP 7
Lumen, Composer, API testing, Microservices, and more
Haafiz Waheed-ud-din Ahmad
BIRMINGHAM - MUMBAI
Building RESTful Web Services with PHP 7
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
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.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: September 2017
Production reference: 1060917
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78712-774-6
www.packtpub.com
Credits
About the Author
Haafiz Waheed-ud-din Ahmad has been working in the IT industry since 2008. He has mostly worked in web application development and mostly used PHP at the server side. Although most of his experience is in PHP, he is a technology agnostic person and also likes to learn and adapt to new technologies. He also acts as an adviser for startups and new developers.
He has worked on Python and JavaScript as well. He likes to experiment with new technologies, and he has also explored Golang, Scala, and Neo4J. He also has a keen interest in data science and big data domain and has worked on D3.js for data visualization. He is not just a technology enthusiast but also likes to solve day-to-day problems by the usage of technology. He blogs at http://haafiz.me/. You can follow him on twitter at @Haafiz786.
About the Reviewer
Shuvankar Sarkar is an IT Analyst experienced in C#, .NET, PHP, and web development. He is a technology enthusiast and maintains a blog at http://shuvankar.com. You can follow him on Twitter at @sonu041. Shuvankar is interested in computer security as well.
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.PacktPub.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.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
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.
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.
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
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
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
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
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
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
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
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
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
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
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.
Although this book is specific to PHP as we will be building RESTful web services in PHP7, it is neither just about PHP7 nor just about REST. RESTful web services and implementation in PHP is what we do in this book. However, you will learn a lot more than that. You will learn about some PHP features that are new in PHP7. We will cover how we should structure our application and some common threats with respect to the web and web services. You will learn how to improve a basic RESTful web service and understand the importance of testing and the different types of testing. So it is not about just REST or PHP, but also about some minor but important programming-related stuff that is simple but makes things a lot better in the real world. At the end of this book, you will learn about an architecture named microservices.
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.
Chapter 2, PHP7, To Code It Better, includes new features and changes in PHP7 that we will either use in this book or are very important and worth discussing.
Chapter 3, Creating RESTful Endpoints, is about creating REST API endpoints for CRUD operations of a blog post in Vanilla PHP. It also explains the manual way of testing API endpoints through a REST client named Postman.
Chapter 4, Reviewing Design Flaws and Security Threats, reviews what we have built in the preceding chapter and highlights the problems and flaws in it so that we can improvise later.
Chapter 5, Load and Resolve with Composer, an Evolutionary, is about an evolutionary tool in the PHP ecosystem: composer. This is not just an autoloader or package installer, but a dependency manager. So, you will learn about composer in this chapter.
Chapter 6, Illuminating RESTful Web Services with Lumen, introduces you to a micro-framework named Lumen, in which we will rewrite our RESTful web services endpoints and review how this tool will significantly improve our speed and application structure.
Chapter 7, Improving RESTful Web Services, equips us to improve what we did in the preceding chapter; you will learn how to improve RESTful web services. We will create authentication and make a Transformer to separate how JSON structure should look. Also, we will improve in terms of security and learn about SSL.
Chapter 8, API Testing – Guards on the Gates, introduces the need of automated tests. Will introduce different type of tests and then focus on API testing. We will then cover an automated testing framework named CodeCeption and write API tests in it.
Chapter 9, Microservices, is about the microservices architecture. We will understand the benefits and challenges of microservices and look into some of possible solutions and trade-offs.
What you need for this book
Although I used Ubuntu, any operating system with PHP7 installed on it will work fine. The only thing required other than PHP7 will be an RDBMS. This book uses MySQL-related settings when connecting to database, so MySQL is ideal, but MariaDB or PostgreSQL will also be fine.
Who this book is for
This book is written for the following audience:
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.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: The randGen() method takes two parameters defining the range of the returned value.
A block of code is set as follows:
function add($num1, $num2):int{
return ($num1+$num2);
}
echo add(2,4); //6
echo add(2.5,4); //6
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
function add($num1, $num2):int{
return ($num1+$num2);
}
echo add(2,4); //6
echo add(2.5,4); //6
Any command-line input or output is written as follows:
sudo add-apt-repository ppa:ondrej/php
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text.
Warnings or important notes appear like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Downloading the example code
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on Code Download.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip