O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Building RESTful Web Services with PHP 7

Book Description

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.

Downloading the example code for this book. You can download the example code files for all Packt books you have purchased 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 code file.

Table of Contents

  1. Preface
    1. What this book covers
    2. What you need for this book
    3. Who this book is for
    4. Conventions
    5. Reader feedback
      1. Downloading the example code
      2. Errata
      3. Piracy
      4. Questions
  2. RESTful Web Services, Introduction and Motivation
    1. Web services
      1. Why a web service?
    2. REST architecture
      1. Client server
      2. Stateless
      3. Cache-able
      4. Uniform interface
        1. Resource identification
        2. Manipulation of resources through representations
        3. Self-descriptive messages
        4. Hypermedia as the engine of application state (HATEOAS)
      5. Code on demand (optional)
      6. Layered system
    3. RESTful web services
      1. Conventions of RESTful web services
      2. HTTP verbs and URL structure
        1. List operation
        2. Create operation
        3. READ operation
        4. Update operation
        5. Delete operation
    4. Why RESTful web services?
      1. REST versus SOAP
    5. Nature of HTTP methods
      1. Safe/unsafe HTTP methods
      2. Idempotent and non-idempotent methods
    6. HTTP response
      1. Response type
      2. Response codes
    7. Case study - RESTful web service endpoints for a blog
      1. Blog post
        1. Requirements
        2. Endpoints
          1. Creating blog post
          2. Reading blog post
          3. Updating blog post
          4. Delete blog post
          5. Listing all blog posts
      2. Blog post comments
        1. Requirements
        2. Endpoints
          1. Creating the post's comment
          2. Reading a comment
          3. Updating a comment
          4. Deleting a post comment
          5. Listing all comments for a particular post
    8. More resources
    9. Summary
  3. PHP7, To Code It Better
    1. Scalar type declaration
    2. Return type declaration
    3. Null coalescing operator
    4. Spaceship operator
    5. Group use declarations
    6. Generator-related features
      1. What are generators?
      2. Generator return expression
      3. Generator delegation
    7. Anonymous classes
    8. Closure::call()
    9. Errors and exceptions
    10. PHP7.1
      1. Nullable types
      2. Symmetric array destructuring
      3. Support for keys in list()
      4. Multi-catch exception handling
    11. More resources
    12. Summary
  4. Creating RESTful Endpoints
    1. Creating a REST API for a blog in PHP
      1. Creating a database schema
        1. Blog user/author table schema
          1. SQL for users table
        2. Blog post table schema
        3. Blog post comments schema
      2. Creating a RESTful API's endpoint
        1. Code structure
        2. Common components
          1. DB class
          2. Router class
          3. Code sync
        3. Creating blog post endpoints
          1. REST client
        4. To do
    2. Visible flaws
      1. Validation
        1. Solution
      2. Authentication
        1. Solution
      3. Proper 404 pages
    3. Summary
  5. Reviewing Design Flaws and Security Threats
    1. Finding problems in the current code
      1. Structural and design flaws
        1. Missing query builder layer
        2. Incomplete router
        3. Usage of OOP
        4. Separate Configurations from Implementation
        5. Should write tests
        6. Input validation
        7. Handling 404 and other errors
        8. Meta information missing
        9. DB fields abstraction
        10. Security
      2. Securing API endpoints
        1. What is Auth middleware?
    2. Common security threats in RESTful web services
      1. Use of HTTPS
      2. Securing an API key/token
        1. Not passing an access token in the URL
        2. Access token expiration
      3. Limited scope access token
      4. Public and private endpoints
        1. Public API endpoints
      5. Insecure direct object reference
      6. Restricting allowable verbs
      7. Input validation
    3. Available reusable code
    4. Summary
  6. Load and Resolve with Composer, an Evolutionary
    1. Introduction to Composer
    2. Installation
      1. Installation on Windows
      2. Installation on Linux/Unix/OS X
        1. Global Installation
    3. Usage of Composer
      1. Composer as a dependency manager
      2. Installing packages
        1. Installing using composer.json
        2. The composer.json in detail
          1. The require object
          2. The require-dev object
          3. The autoload and autoload-dev
          4. The scripts
        3. The composer.lock
      3. Composer as an auto-loader
        1. Example
      4. Composer for creating a project
        1. Example
    4. Summary
  7. Illuminating RESTful Web Services with Lumen
    1. Introducing Lumen
      1. Why micro-framework?
      2. Why Lumen?
      3. What Lumen provides
        1. What Lumen has in common with Laravel
        2. How Lumen is different from Laravel
        3. What exactly Lumen provides
          1. A Good Structure
          2. Separate configurations
          3. Router
          4. Middle-wares
          5. Service Container and Dependency Injection
          6. HTTP responses
          7. Validation
          8. Eloquent ORM
          9. Database migration and seeding
          10. Unit testing
    2. Installing Lumen
      1. Configuration
    3. Setting up the database
      1. Writing migrations
    4. Writing RESTful web service endpoints
      1. Writing the first controller
      2. Lumen routes
      3. REST resource
      4. Eloquent ORM (model layer)
        1. Creating models
        2. Eloquent relationships
    5. Controller Implementation
    6. What we are missing?
      1. Validation and negative cases?
        1. /api/posts with GET method
        2. /api/posts with the POST method
        3. /api/posts/1 with the GET method
        4. /api/posts/1 with the PATCH/PUT method
        5. /api/posts/1 with the DELETE method
      2. User authentication
      3. Other missing elements
      4. Comment Resource Implementation
    7. Summary
  8. Improving RESTful Web Services
    1. Dingo, simplifying RESTful API development
      1. Installation and configuration
      2. Simplifying routes
      3. API versioning
      4. Rate limiting
      5. Internal requests
      6. Responses
    2. Authentication and middleware
      1. JWT Auth setup
        1. The Manual way
        2. Simpler way through Lumen JWT authentication integration package
      2. Authentication
        1. Log in
        2. Invalidate token
        3. Refresh token
    3. Transformers
      1. Understanding and setting transformers
      2. Using transformers
    4. Encryption
      1. SSL certificate, different options
    5. Summary
  9. API Testing – Guards on the Gates
    1. The need for automated tests
    2. Types of testing
      1. Unit testing
      2. Acceptance testing
      3. Functional testing
      4. Integration testing
    3. What type of testing will we do?
    4. Testing frameworks
      1. CodeCeption introduction
      2. Setup and understanding the structure
        1. tests/{suite-name}/
        2. tests/{suite-name}.suite.yml
        3. tests/_support/_generated/{suite-name}TesterActions.php
        4. tests/_support/{suite-name}Tester.php
        5. tests/_support/Helper/{suite-name}.php
        6. Creating the API suite
        7. Configuring the API suite
      3. Writing test cases
        1. API tests for post resource
        2. Other test cases
    5. Summary
      1. More resources
  10. Microservices
    1. Introducing Microservices
      1. How to divide an application into microservices?
    2. Motivation towards microservices
      1. Maintenance and debugging
      2. Scalability
      3. Technology diversity
      4. Resilience
      5. Replaceability
      6. Parallelization
    3. How it is different from SOA
    4. Team structure
    5. Challenges of micro-services
      1. Infrastructure maintenance
      2. Performance
      3. Debugging and fault-finding
        1. Logs should be centralized
        2. Logs should be searchable
        3. Track chain of requests
        4. Dynamic log levels
    6. Implementation
      1. Deployments
      2. Inter-services communication
        1. Synchronous communication
        2. Asynchronous communication
      3. Shared library or common code
    7. Summary
      1. What's next