SlideShare a Scribd company logo
PSR-7
A SET OF COMMON INTERFACES FOR HTTP
MESSAGES
by Marco Perone / @marcoshuttle
HTTP MESSAGES
HTTP MESSAGE STRUCTURE
    <message line>
    Header: value
    Another­Header: value
    Message body
BODY
string
handled by server and clients as a stream
PHP natively represents it using streams
REQUEST MESSAGE LINE
METHOD REQUEST-TARGET HTTP/VERSION
REQUEST TARGET
origin form
absolute form
authority form
asterisk form
URI
SCHEME://AUTHORITY[/PATH][?QUERY
STRING]
AUTHORITY = [USER[:PASS]@]HOST[:PORT]
RESPONSE MESSAGE LINE
HTTP/VERSION STATUS REASON
USE OF HTTP MESSAGES IN PHP
USE CASE 1
USE PHP SUPERGLOBALS
Any application before frameworks
USE CASE 2
CREATE NEW IMPLEMENTATION FROM
SCRATCH
Frameworks define http components
Single purpose libraries (oauth-server-php)
Http clients ad Guzzle and Buzz
USE CASE 3
REQUIRE A SPECIFIC HTTP CLIENT/SERVER
LIBRARY PROVIDING MESSAGE
IMPLEMENTATION
Silex, Stack, Drupal 8 have hard dependencies on Symfony's
HTTP kernel
Any SDK developed with Guzzle has a hard requirement on
Guzzle's HTTP message implementations
USE CASE 4
CREATE ADAPTERS FOR COMMON HTTP
MESSAGE IMPLEMENTATIONS
Projects such as Geocoder create redundant adapters for
common libraries
PROBLEMS
Superglobals are mutable. Libraries can alter state of the
application
Unit and integration testing difficult
Projects not capable of interoperability or cross-
pollination
Necessity of building a bridge layer between applications
Any content emitted before a call to header()will result
in that a call becoming a no-op
THE SCOPE OF PSR-7
GOALS
Provide the interfaces needed for describing HTTP
messages
Focus on practical applications and usability
Define the interfaces to model all elements of the HTTP
message and URI specifications
Ensure that the API does not impose arbitrary limits on
HTTP messages
Provide useful abstractions both for handling incoming
requests for server-side applications and for sending
outgoing requests in HTTP clients
NON GOALS
Does not expect all HTTP client libraries or server-side
frameworks to change their interfaces to conform. It is
strictly meant for interoperability
Should not impose implementation details
USE CASES
CLIENTS
Unified message interface to use for making requests
$response = $client­>send($request);
                        
MIDDLEWARES
Function that accepts request and response as parameters
and does something with them, including delegating to the
next middleware
function (
    ServerRequestInterface $request,
    ResponseInterface $response,
    callable $next = null
) {
    # do stuff here
}
                        
FRAMEWORKS
They did HTTP message abstraction since a long time
PSR-7 provides a common set of interfaces
Consider ZendStdlibDispatchableInterfacein
Zend Framework 2
use ZendHttpRequestInterface;
use ZendHttpResponseInterface;
interface DispatchableInterface
{
    public function dispatch(
        RequestInterface $request,
        ResponseInterface $response
    );
}
                        
PSR-7 BY EXAMPLES
INTERMEZZO: VALUE OBJECTS
Messages and URIs are modeled as value objects
a change to any aspect of the message is essentially a new
message
immutability
ensure integrity of message state
use a base instance as prototype
MESSAGES
namespace PsrHttpMessage;
MessageInterface
ResponseInterface
RequestInterface
ServerRequestInterface
HEADERS
// Returns null if not found:
$header = $message­>getHeader('Accept');
// Test for a header:
if (! $message­>hasHeader('Accept')) {
}
// If the header has multiple values, fetch them
// as an array:
$values = $message­>getHeaderLines('X­Foo');
                            
HEADERS
/* Returns the following structure:
    [
        'Header' => [
            'value1'
            'value2'
        ]
    ]
*/
foreach ($message­>getAllHeaders() as $header => $values) {
}
                            
HEADERS
$new = $message­>withHeader('Location', 'http://example.com');
$message = $message­>withHeader('Location', 'http://example.com');
$message = $message­>withAddedHeader('X­Foo', 'bar');
$message = $message­>withoutHeader('X­Foo');
                            
BODIES
treated as streams
StreamableInterfaceis used
$body = new Stream('php://temp');
$body­>write('Here is the content for my message!');
$message = $message­>withBody(new Stream('php://temp'));
                        
RESPONSES
status code
reason phrase
$status = $response­>getStatusCode();
$reason = $response­>getReasonPhrase();
$response = $response­>withStatus(418, "I'm a teapot");
                        
REQUESTS
method
request target
REQUEST TARGET AND URI
The request interface:
composes a UriInterfaceinstance, which models the
URI itself
provides two methods around request-targets:
getRequestTarget()and
withRequestTarget()
URI INTERFACE
URI are treated as value objects
    // URI parts:
    $scheme    = $uri­>getScheme();
    $userInfo  = $uri­>getUserInfo();
    $host      = $uri­>getHost();
    $port      = $uri­>getPort();
    $path      = $uri­>getPath();
    $query     = $uri­>getQuery();     // the query STRING
    $authority = $uri­>getAuthority(); // [user­info@]host[:port]
    $uri = $uri
        ­>withScheme('http')
        ­>withHost('example.com')
        ­>withPath('/foo/bar')
        ­>withQuery('?baz=bat');
                            
CREATE REQUEST
    $request = $request
        ­>withMethod('OPTION')
        ­>withUri($uri­>withPath('/api/user'))
        ­>withRequestTarget('*');
                            
SERVER SIDE REQUESTS
PHP's Server API does a number of things for us:
Deserialization of query string arguments ($_GET)
Deserialization of urlencoded form data submitted via
POST ($_POST)
Deserialization of cookies ($_COOKIE)
Identification and handling of file uploads ($_FILES)
Encapsulation of CGI/SAPI parameters ($_SERVER)
SERVER SIDE REQUESTS
ServerRequestInterfaceextends the base
RequestInterfaceand offers features around these
values
$query   = $request­>getQueryParams();
$body    = $request­>getParsedBody();
$cookies = $request­>getCookieParams();
$files   = $request­>getFileParams();
$server  = $request­>getServerParams();
                            
ATTRIBUTES
$request­>getAttribute($name, $default = null);
$request­>getAttributes();
$request = $request­>withAttribute($name, $value);
$request = $request­>withoutAttribute();
                            
REFERENCES
by
FIG PSR-7 metadocument
FIG PSR-7 specifications
PSR-7 by example @mwop

More Related Content

PDF
Psr 7 symfony-day
Marco Perone
 
PDF
8 Minutes On Rack
danwrong
 
PDF
Rack Middleware
LittleBIGRuby
 
ODP
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
King Foo
 
PDF
PHP And Web Services: Perfect Partners
Lorna Mitchell
 
PPT
Oracle database - Get external data via HTTP, FTP and Web Services
Kim Berg Hansen
 
PDF
Flask patterns
it-people
 
PDF
170517 damien gérard framework facebook
Geeks Anonymes
 
Psr 7 symfony-day
Marco Perone
 
8 Minutes On Rack
danwrong
 
Rack Middleware
LittleBIGRuby
 
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
King Foo
 
PHP And Web Services: Perfect Partners
Lorna Mitchell
 
Oracle database - Get external data via HTTP, FTP and Web Services
Kim Berg Hansen
 
Flask patterns
it-people
 
170517 damien gérard framework facebook
Geeks Anonymes
 

What's hot (20)

PPTX
RESTful API 제대로 만들기
Juwon Kim
 
PDF
用Tornado开发RESTful API运用
Felinx Lee
 
PDF
Rest API using Flask & SqlAlchemy
Alessandro Cucci
 
PDF
Web services tutorial
Lorna Mitchell
 
PPTX
Flask restfulservices
Marcos Lin
 
ODP
REST API Laravel
John Dave Decano
 
PPTX
Zephir - A Wind of Change for writing PHP extensions
Mark Baker
 
PPT
Rapid java backend and api development for mobile devices
ciklum_ods
 
PDF
RESTful API Design & Implementation with CodeIgniter PHP Framework
Bo-Yi Wu
 
PDF
JSON-RPC Proxy Generation with PHP 5
Stephan Schmidt
 
PPT
Real time server
thepian
 
PPT
Jsp/Servlet
Sunil OS
 
PDF
Flask - Backend com Python - Semcomp 18
Lar21
 
PDF
Information security programming in ruby
Hiroshi Nakamura
 
PDF
Flask RESTful Flask HTTPAuth
Eueung Mulyana
 
PPT
JAVA Servlets
deepak kumar
 
PPTX
Flask – Python
Max Claus Nunes
 
PDF
JSON-RPC - JSON Remote Procedure Call
Peter R. Egli
 
PDF
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
CodeCore
 
PDF
Introduction to PowerShell
Boulos Dib
 
RESTful API 제대로 만들기
Juwon Kim
 
用Tornado开发RESTful API运用
Felinx Lee
 
Rest API using Flask & SqlAlchemy
Alessandro Cucci
 
Web services tutorial
Lorna Mitchell
 
Flask restfulservices
Marcos Lin
 
REST API Laravel
John Dave Decano
 
Zephir - A Wind of Change for writing PHP extensions
Mark Baker
 
Rapid java backend and api development for mobile devices
ciklum_ods
 
RESTful API Design & Implementation with CodeIgniter PHP Framework
Bo-Yi Wu
 
JSON-RPC Proxy Generation with PHP 5
Stephan Schmidt
 
Real time server
thepian
 
Jsp/Servlet
Sunil OS
 
Flask - Backend com Python - Semcomp 18
Lar21
 
Information security programming in ruby
Hiroshi Nakamura
 
Flask RESTful Flask HTTPAuth
Eueung Mulyana
 
JAVA Servlets
deepak kumar
 
Flask – Python
Max Claus Nunes
 
JSON-RPC - JSON Remote Procedure Call
Peter R. Egli
 
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
CodeCore
 
Introduction to PowerShell
Boulos Dib
 
Ad

Similar to Psr-7 (20)

PPTX
JAX-RS 2.0 and OData
Anil Allewar
 
PDF
Building RESTful applications using Spring MVC
IndicThreads
 
PDF
Rest web service
Hamid Ghorbani
 
ODP
Creating Web Services with Zend Framework - Matthew Turland
Matthew Turland
 
ODP
SCDJWS 5. JAX-WS
Francesco Ierna
 
PPT
Restful API's with ColdFusion
ColdFusionConference
 
PDF
Networked APIs with swift
Tim Burks
 
PPT
KaTe RESTful adapter for SAP Process Integration: Introduction
Kate_RESTful
 
PDF
RESTEasy
Massimiliano Dessì
 
PPTX
Asp.net web api
Binu Bhasuran
 
PPTX
Rest presentation
srividhyau
 
PDF
767458168-Introduction-to-Web-API767458168-Introduction-to-Web-API.pdf.pdf
ssuser16fbed
 
PPTX
Restful webservices
Kong King
 
PPTX
Slim Framework
Pramod Raghav
 
PDF
May 2010 - RestEasy
JBug Italy
 
PPT
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
Matt O'Keefe
 
PDF
Building Restful Applications Using Php
Sudheer Satyanarayana
 
PDF
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Joshua Long
 
PPTX
ASP.NET WEB API Training
Chalermpon Areepong
 
PPTX
Spring mvc
Harshit Choudhary
 
JAX-RS 2.0 and OData
Anil Allewar
 
Building RESTful applications using Spring MVC
IndicThreads
 
Rest web service
Hamid Ghorbani
 
Creating Web Services with Zend Framework - Matthew Turland
Matthew Turland
 
SCDJWS 5. JAX-WS
Francesco Ierna
 
Restful API's with ColdFusion
ColdFusionConference
 
Networked APIs with swift
Tim Burks
 
KaTe RESTful adapter for SAP Process Integration: Introduction
Kate_RESTful
 
Asp.net web api
Binu Bhasuran
 
Rest presentation
srividhyau
 
767458168-Introduction-to-Web-API767458168-Introduction-to-Web-API.pdf.pdf
ssuser16fbed
 
Restful webservices
Kong King
 
Slim Framework
Pramod Raghav
 
May 2010 - RestEasy
JBug Italy
 
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
Matt O'Keefe
 
Building Restful Applications Using Php
Sudheer Satyanarayana
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Joshua Long
 
ASP.NET WEB API Training
Chalermpon Areepong
 
Spring mvc
Harshit Choudhary
 
Ad

Recently uploaded (20)

PPTX
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
PDF
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
PDF
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
PPTX
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PDF
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PPT
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PPTX
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PDF
Exploring AI Agents in Process Industries
amoreira6
 
PDF
Protecting the Digital World Cyber Securit
dnthakkar16
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PPTX
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
PPTX
Presentation about Database and Database Administrator
abhishekchauhan86963
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PDF
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
Presentation about variables and constant.pptx
kr2589474
 
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
Activate_Methodology_Summary presentatio
annapureddyn
 
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
Exploring AI Agents in Process Industries
amoreira6
 
Protecting the Digital World Cyber Securit
dnthakkar16
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
Presentation about Database and Database Administrator
abhishekchauhan86963
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 

Psr-7