70
Making the Most of HTTP In Your Apps Ben Ramsey • Dutch PHP Conference 22 May 2009

Making the Most of HTTP In Your Applications

Embed Size (px)

DESCRIPTION

200, 404, 302. Is it a lock combination? A phone number? No, they're HTTP status codes! As we develop Web applications, we encounter these status codes and others, and often we make decisions about which ones to return without giving much thought to their meaning or context. It's time to take a deeper look at HTTP. Knowing the methods, headers, and status codes, what they mean, and how to use them can help you develop richer Internet applications. Join Ben Ramsey as he takes you on a journey through RFC 2616 to discover some of the gems of HTTP.

Citation preview

Page 1: Making the Most of HTTP In Your Applications

Making the Most of HTTP In Your Apps

Ben Ramsey • Dutch PHP Conference22 May 2009

Page 2: Making the Most of HTTP In Your Applications

Why HTTP?

Page 3: Making the Most of HTTP In Your Applications

Because you are a Web developer.

Page 4: Making the Most of HTTP In Your Applications

HTTP is the Web.

Page 5: Making the Most of HTTP In Your Applications

That’s all I have to say about that.

Page 6: Making the Most of HTTP In Your Applications

Some properties of HTTP...

Page 7: Making the Most of HTTP In Your Applications

❖ A client-server architecture

❖ Atomic

❖ Cacheable

❖ A uniform interface

❖ Layered

❖ Code on demand

Page 8: Making the Most of HTTP In Your Applications

Now, what does that sound like?

Page 9: Making the Most of HTTP In Your Applications

REST!

Page 10: Making the Most of HTTP In Your Applications

And, that’s all I have to say about that, too.

Page 11: Making the Most of HTTP In Your Applications

Our focus today...

Page 12: Making the Most of HTTP In Your Applications

❖ Methods

❖ Status Codes

❖ Playing with raw HTTP

❖ HTTP in PHP

Page 13: Making the Most of HTTP In Your Applications

Defining safe & idempotentmethods

Page 14: Making the Most of HTTP In Your Applications

Safe methods

❖ GET & HEAD should not take action other than retrieval

❖ These are considered safe

❖ Allows agents to represent POST, PUT, & DELETE in a special way

Page 15: Making the Most of HTTP In Your Applications

Idempotence

❖ Side-effects of N > 0 identical requests is the same as for a single request

❖ GET, HEAD, PUT and DELETE share this property

❖ OPTIONS and TRACE are inherently idempotent

Page 16: Making the Most of HTTP In Your Applications

Methods

Page 17: Making the Most of HTTP In Your Applications

❖ Retrieval of information

❖ Transfers a representation of a resource from the server to the client

❖ Safe

❖ Idempotent

GET

Page 18: Making the Most of HTTP In Your Applications

HEAD

❖ Identical to GET, except...

❖ Returns only the headers, not the body

❖ Useful for getting details about a resource representation before retrieving the full representation

❖ Safe

❖ Idempotent

Page 19: Making the Most of HTTP In Your Applications

POST

❖ The body content should be accepted as a new subordinate of the resource

❖ Append, annotate, paste after

❖ Not safe

❖ Non-idempotent

Page 20: Making the Most of HTTP In Your Applications

PUT

❖ Opposite of GET

❖ Storage of information

❖ Transfers a representation of a resource from the client to the server

❖ Not safe

❖ Idempotent

Page 21: Making the Most of HTTP In Your Applications

DELETE

❖ Requests that the resource identified be removed from public access

❖ Not safe

❖ Idempotent

Page 22: Making the Most of HTTP In Your Applications

Other methods

❖ OPTIONS

❖ TRACE

❖ CONNECT

Page 23: Making the Most of HTTP In Your Applications

Status codes

Page 24: Making the Most of HTTP In Your Applications

❖ Informational (1xx)

❖ Successful (2xx)

❖ Redirection (3xx)

❖ Client error (4xx)

❖ Server error (5xx)

Page 25: Making the Most of HTTP In Your Applications

Informational (1xx)

Page 26: Making the Most of HTTP In Your Applications

100 Continue

Page 27: Making the Most of HTTP In Your Applications

1. Client sends a request without a body and includes the Expect: 100-continue header and all other headers

2. Server determines whether it will accept the request and responds with 100 Continue (or a 4xx code on error)

3. Client sends the request again with the body and without the Expect header

Page 28: Making the Most of HTTP In Your Applications

1

POST /content/videos HTTP/1.1Host: example.orgContent-Type: video/mp4Content-Length: 115910000Authorization: Basic bWFkZTp5b3VfbG9vaw==Expect: 100-continue

Page 29: Making the Most of HTTP In Your Applications

2

HTTP/1.1 413 Request Entity Too LargeDate: Thu, 21 May 2009 23:05:15 GMTServer: Apache/2.2.11 (Unix) DAV/2 PHP/5.3.0RC2X-Powered-By: PHP/5.3.0RC2Content-Length: 0Connection: closeContent-Type: text/html

Failure state

Page 30: Making the Most of HTTP In Your Applications

2

HTTP/1.1 100 ContinueDate: Thu, 21 May 2009 23:05:15 GMTServer: Apache/2.2.11 (Unix) DAV/2 PHP/5.3.0RC2X-Powered-By: PHP/5.3.0RC2Content-Length: 0Content-Type: text/html

Success state

Page 31: Making the Most of HTTP In Your Applications

3

POST /content/videos HTTP/1.1Host: example.orgContent-Type: video/mp4Content-Length: 115910000Authorization: Basic bWFkZTp5b3VfbG9vaw==

{binary video data}

Page 32: Making the Most of HTTP In Your Applications

4

HTTP/1.1 201 CreatedDate: Thu, 21 May 2009 23:05:34 GMTServer: Apache/2.2.11 (Unix) DAV/2 PHP/5.3.0RC2X-Powered-By: PHP/5.3.0RC2Content-Length: 119Content-Type: text/htmlLocation: http://example.org/content/videos/1234

<html><body><p>Video uploaded! Go <a href="http://example.org/content/videos/1234">here</a> to see it.</p></body></html>

Page 33: Making the Most of HTTP In Your Applications

Successful (2xx)

Page 34: Making the Most of HTTP In Your Applications

200 OKGET /content/videos/1234 HTTP/1.1Host: example.org

HTTP/1.x 200 OKDate: Thu, 21 May 2009 23:08:35 GMTServer: Apache/2.2.11 (Unix) DAV/2 PHP/5.3.0RC2X-Powered-By: PHP/5.3.0RC2Content-Type: video/mp4Content-Length: 115910000

{binary data}

Page 35: Making the Most of HTTP In Your Applications

201 Created

1

POST /content/videos HTTP/1.1Host: example.orgContent-Type: video/mp4Content-Length: 115910000Authorization: Basic bWFkZTp5b3VfbG9vaw==

{binary video data}

Page 36: Making the Most of HTTP In Your Applications

201 Created

2

HTTP/1.x 201 CreatedDate: Thu, 21 May 2009 23:05:34 GMTServer: Apache/2.2.11 (Unix) DAV/2 PHP/5.3.0RC2X-Powered-By: PHP/5.3.0RC2Content-Length: 120Content-Type: text/htmlLocation: http://example.org/content/videos/1234

<html><body><p>Video uploaded! Go <a href="http://example.org/content/videos/1234">here</a> to see it.</p></body></html>

Page 37: Making the Most of HTTP In Your Applications

202 Accepted

2

HTTP/1.x 202 AcceptedDate: Thu, 21 May 2009 23:05:34 GMTServer: Apache/2.2.11 (Unix) DAV/2 PHP/5.3.0RC2X-Powered-By: PHP/5.3.0RC2Content-Length: 137Content-Type: text/htmlLocation: http://example.org/content/videos/1234/status

<html><body><p>Video processing! Check <a href="http://example.org/content/videos/1234/status">here</a> for the status.</p></body></html>

Page 38: Making the Most of HTTP In Your Applications

204 No Content

1

DELETE /content/videos/1234 HTTP/1.1Host: example.orgAuthorization: Basic bWFkZTp5b3VfbG9vaw==

Page 39: Making the Most of HTTP In Your Applications

204 No Content

2

HTTP/1.x 204 No ContentDate: Thu, 21 May 2009 23:28:34 GMT

Page 40: Making the Most of HTTP In Your Applications

205 Reset Content

“The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent. This response is primarily intended to allow input for actions to take place via user input, followed by a clearing of the form in which the input is given so that the user can easily initiate another input action.”

Page 41: Making the Most of HTTP In Your Applications

206 Partial Content

❖ Used when requests are made for ranges of bytes from a resource

❖ Determine whether a server supports range requests by checking for the Accept-Ranges header with HEAD

Page 42: Making the Most of HTTP In Your Applications

1

HEAD /2390/2253727548_a413c88ab3_s.jpg HTTP/1.1Host: farm3.static.flickr.com

Page 43: Making the Most of HTTP In Your Applications

2

HTTP/1.0 200 OKDate: Mon, 05 May 2008 00:33:14 GMTServer: Apache/2.0.52 (Red Hat)Accept-Ranges: bytesContent-Length: 3980Content-Type: image/jpeg

Page 44: Making the Most of HTTP In Your Applications

3

GET /2390/2253727548_a413c88ab3_s.jpg HTTP/1.1Host: farm3.static.flickr.comRange: bytes=0-999

Page 45: Making the Most of HTTP In Your Applications

4

HTTP/1.0 206 Partial ContentDate: Mon, 05 May 2008 00:36:57 GMTServer: Apache/2.0.52 (Red Hat)Accept-Ranges: bytesContent-Length: 1000Content-Range: bytes 0-999/3980Content-Type: image/jpeg

{binary data}

Page 46: Making the Most of HTTP In Your Applications

Redirection (3xx)

Page 47: Making the Most of HTTP In Your Applications

303 See Other

❖ The response to your request can be found at another URL identified by the Location header

❖ The client should make a GET request on that URL

❖ The Location is not a substitute for this URL

Page 48: Making the Most of HTTP In Your Applications

307 Temporary Redirect❖ The resource resides temporarily at the

URL identified by the Location

❖ The Location may change, so don’t update your links

❖ If the request is not GET or HEAD, then you must allow the user to confirm the action

Page 49: Making the Most of HTTP In Your Applications

302 Found

❖ The resource has been found at another URL identified by the Location header

❖ The new URL might be temporary, so the client should continue to use this URL

❖ Redirections SHOULD be confirmed by the user (in practice, browsers don’t respect this)

Page 50: Making the Most of HTTP In Your Applications

301 Moved Permanently

❖ The resource has moved permanently to the URL indicated by the Location header

❖ You should update your links accordingly

❖ Great for forcing search engines, etc. to index the new URL instead of this one

Page 51: Making the Most of HTTP In Your Applications

Client error (4xx)

Page 52: Making the Most of HTTP In Your Applications

❖ 400 Bad Request

❖ 401 Unauthorized / 403 Forbidden

❖ 404 Not Found

❖ 405 Method Not Allowed

❖ 410 Gone

Page 53: Making the Most of HTTP In Your Applications

❖ 411 Length Required

❖ 413 Request Entity Too Large

❖ 415 Unsupported Media Type

❖ 416 Requested Range Not Satisfiable

Page 54: Making the Most of HTTP In Your Applications

Server error (5xx)

Page 55: Making the Most of HTTP In Your Applications

❖ 500 Internal Server Error

❖ 503 Service Unavailable

Page 56: Making the Most of HTTP In Your Applications

Manipulating raw HTTP

Page 57: Making the Most of HTTP In Your Applications

[bramsey@pippin ~] telnet phparch.com 80

Page 58: Making the Most of HTTP In Your Applications

[bramsey@pippin ~] telnet phparch.com 80Trying 64.34.173.96...Connected to phparch.com.Escape character is '^]'.

Page 59: Making the Most of HTTP In Your Applications

[bramsey@pippin ~] telnet phparch.com 80Trying 64.34.173.96...Connected to phparch.com.Escape character is '^]'.HEAD / HTTP/1.1Host: phparch.com

Page 60: Making the Most of HTTP In Your Applications

[bramsey@pippin ~] telnet phparch.com 80Trying 64.34.173.96...Connected to phparch.com.Escape character is '^]'.HEAD / HTTP/1.1Host: phparch.com

HTTP/1.1 200 OKDate: Thu, 21 May 2009 21:01:06 GMTServer: Apache/2.2.9 (Debian) PHP/5.2.5 mod_ssl/2.2.9 OpenSSL/0.9.8gX-Powered-By: PHP/5.2.5Set-Cookie: PHPSESSID=eeeff50d3b6ae241c934a5c2671b0005; expires=Sun, 21 Jun 2009 21:01:07 GMT; path=/; domain=.phparch.comExpires: Thu, 19 Nov 1981 08:52:00 GMTCache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0Pragma: no-cacheContent-Type: text/html; charset=utf-8

Connection closed by foreign host.

Page 61: Making the Most of HTTP In Your Applications

Using HTTP in PHP

Page 62: Making the Most of HTTP In Your Applications

❖ header() functionhttp://php.net/header

❖ Client URL library (cURL)http://php.net/curl

❖ Streamshttp://php.net/streams

❖ HTTP extension (pecl/http)http://php.net/http

Page 63: Making the Most of HTTP In Your Applications

header() example

Page 64: Making the Most of HTTP In Your Applications

<?php

header('HTTP/1.x 201 Created');header('Content-Type: application/xml');header('Location: http://example.org/content/videos/1234');

echo $htmlBody;

?>

Page 65: Making the Most of HTTP In Your Applications

HTTP/1.1 201 CreatedDate: Fri, 12 Jun 2009 13:53:38 GMTServer: Apache/2.2.11 (Unix) DAV/2 PHP/5.3.0RC2X-Powered-By: PHP/5.3.0RC2Location: http://example.org/content/videos/1234Content-Length: 120Content-Type: text/html

<html><body><p>Video uploaded! Go <a href="http://example.org/content/videos/1234">here</a> to see it.</p></body></html>

Page 66: Making the Most of HTTP In Your Applications

cURL example

Page 67: Making the Most of HTTP In Your Applications

// Send a DM to a Twitter friend$dm = array(    'user' => 'ramsey',    'text' => 'Hi! I\'m using your curl code!');

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL,  "http://twitter.com/direct_messages/new.json");curl_setopt($curl, CURLOPT_POST, true);curl_setopt($curl, CURLOPT_POSTFIELDS, $dm);curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);curl_setopt($curl, CURLOPT_USERPWD,  "{$username}:{$password}");curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

// Suppress the Expect: 100-continue header that // cURL tries to sendcurl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:'));

$response = curl_exec($curl);curl_close($curl);

Page 68: Making the Most of HTTP In Your Applications

{"text":"Hi! I'm using your curl code!","sender":{"notifications":false,"profile_text_color":"333333","profile_image_url":"http:\/\/s3.amazonaws.com\/twitter_production\/profile_images\/66941217\/phpc_normal.png","description":"PHPC is a gathering place for the PHP community. It is about community and friendship.","profile_background_image_url":"http:\/\/s3.amazonaws.com\/twitter_production\/profile_background_images\/3561102\/php2.png","utc_offset":-18000,"time_zone":"Eastern Time (US & Canada)","created_at":"Tue Dec 09 18:05:32 +0000 2008","profile_link_color":"333366","screen_name":"phpc","profile_background_tile":false,"followers_count":2163,"profile_background_color":"000000","url":"http:\/\/phpcommunity.org\/","name":"PHP Community","friends_count":2146,"protected":false,"statuses_count":213,"profile_sidebar_fill_color":"d4d5e8","profile_sidebar_border_color":"333333","following":false,"favourites_count":0,"location":"#phpc on Freenode IRC","id":17997273,"verified_profile":false},"created_at":"Fri Jun 12 14:08:34 +0000 2009","sender_id":17997273,"sender_screen_name":"phpc","recipient_screen_name":"ramsey","recipient_id":7794552,"id":170497722,"recipient":{"notifications":false,"profile_text_color":"000000","profile_image_url":"http:\/\/s3.amazonaws.com\/twitter_production\/profile_images\/81619004\/bramsey-square_normal.png","description":"Dad, Software Architect, PHP, XML, web services, beer drinker, libertarian","profile_background_image_url":"http:\/\/static.twitter.com\/images\/themes\/theme1\/bg.gif","utc_offset":-18000,"time_zone":"Eastern Time (US & Canada)","created_at":"Sun Jul 29 02:44:40 +0000 2007","profile_link_color":"0066CC","screen_name":"ramsey","profile_background_tile":false,"followers_count":817,"profile_background_color":"666666","url":"http:\/\/benramsey.com\/","name":"Ben Ramsey","friends_count":187,"protected":false,"statuses_count":5062,"profile_sidebar_fill_color":"99ff66","profile_sidebar_border_color":"33cc00","following":0,"favourites_count":23,"location":"Atlanta, GA, US","id":7794552,"verified_profile":false}}

Page 69: Making the Most of HTTP In Your Applications

Questions?

❖ My website is benramsey.com

❖ Rate this talk at joind.in/576

❖ Read the HTTP spec attools.ietf.org/html/rfc2616

❖ My company is Schematicschematic.com