El protocol Hypertext Transfer Protocol és un protocol de nivell d'aplicació per a sistemes d'informació distribuits, col·laboratius i amb hypermedia. És un protocol sense estat
Llista amb els seus enllaços
Consulteu HTML#Redireccions.
Recursos:
Es poden indicar capçaleres de request amb:
$ http example.org User-Agent:Bacon/1.0 'Cookie:valued-visitor=yes;foo=bar' X-Foo:Bar Referer:http://httpie.org/
Conté el nom de domini del servidor i el port demanat durant la petició. Sinó s'indica el port de suposa el port per defecte. Exemples:
Host: en.wikipedia.org:8080 Host: en.wikipedia.org
IMPORTANT: Aquest camp és obligatori des de la versió HTTP1.1
Cal tenir en compte que tot i que pot semblar redundant per que la informació ja està a la URL això no és cert. A les peticions HTTP no va la URL completa sinó només la URI és a dir precisament el que va després del nom de servidor i port.
Els servidors utilitzen aquesta informació per exemple per implementar Virtual Hosting (mateixa IP física, múltiples pàgines/dominis web)
Indica el tipus del navegador. Es pot utilitzar per a fer estadístiques de visites però millor no utilitzar (mala pràctica i evidentment no segura) per a servir diferent contingut depenen del navegador
Conté un email.No és un camp obligatori i s'utilitza per posar una adreça de contacte del qui realitza les peticions. Els navegadors no ho posen però està pensat per aplicacions robot tipus spiders poder posar una adreça de contacte per posar-se en contacte amb l'autor de l'aranya.
Resources
The Authorization request-header field value consists of credentials containing the authentication information of the user agent for the realm of the resource being requested. The general syntax is:
Authorization : credentials
The HTTP/1.0 specification defines the BASIC authorization scheme, where the authorization parameter is the string of username:password encoded in base 64. Following is an example:
Authorization: BASIC Z3Vlc3Q6Z3Vlc3QxMjM=
The value decodes into is guest:guest123 where guest is user ID and guest123 is the password.
Vegeu Cookies
The Cookie request-header field value contains a name/value pair of information stored for that URL. Following is the general syntax:
Cookie: name=value
Multiple cookies can be specified separated by semicolons as follows:
Cookie: name1=value1;name2=value2;name3=value3
Exemple manual:
Pàgina origen:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <a href="headers.php">Link to header1.php</a> </body> </html>
Fitxer headers.php:
<?php var_dump(getallheaders());
El resultat després de seguir el link és:
/home/sergi/HTTP/prova/header1.php:3: array (size=9) ... 'User-Agent' => string 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36' (length=105) 'Referer' => string 'http://127.0.0.1:8000/paginaorigen.html' (length=39)
Resources:
header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized');
Dos tipus, el primer per indicar el codi de resposta:
header("HTTP/1.1 404 Not Found");
O per a un header en si mateix:
header("Location: http://www.example.com/"); /* Redirect browser */
També coneguts com a HTTP verbs
Recursos
Vegeu també:
Vegeu les diferències a:
http://www.w3schools.com/tags/ref_httpmethods.asp
Vegeu Formularis HTML
HTTP status codes in the response body tells client application what action should be taken with the response. For an example if the response code 200, it means on the server side the request is processed successfully and you can expect updated data in the response. As well if the status code is 401, the request is not authorized. An example cause for 401 could be api key is invalid.
It is not necessary to support all HTTP status codes, but supporting at least the following codes should be good enough. Check out list of http codes from restapitutorial.com and Wikipedia
200 OK 201 Created 304 Not Modified 400 Bad Request 401 Unauthorized 403 Forbidden 404 Not Found 422 Unprocessable Entity 500 Internal Server Error
Llista completa:
http://www.rfc-editor.org/rfc/rfc2616.txt
Status-Code = "100" ; Section 10.1.1: Continue | "101" ; Section 10.1.2: Switching Protocols | "200" ; Section 10.2.1: OK | "201" ; Section 10.2.2: Created | "202" ; Section 10.2.3: Accepted | "203" ; Section 10.2.4: Non-Authoritative Information | "204" ; Section 10.2.5: No Content | "205" ; Section 10.2.6: Reset Content | "206" ; Section 10.2.7: Partial Content | "300" ; Section 10.3.1: Multiple Choices | "301" ; Section 10.3.2: Moved Permanently | "302" ; Section 10.3.3: Found | "303" ; Section 10.3.4: See Other | "304" ; Section 10.3.5: Not Modified | "305" ; Section 10.3.6: Use Proxy | "307" ; Section 10.3.8: Temporary Redirect | "400" ; Section 10.4.1: Bad Request | "401" ; Section 10.4.2: Unauthorized | "402" ; Section 10.4.3: Payment Required | "403" ; Section 10.4.4: Forbidden | "404" ; Section 10.4.5: Not Found | "405" ; Section 10.4.6: Method Not Allowed | "406" ; Section 10.4.7: Not Acceptable | "407" ; Section 10.4.8: Proxy Authentication Required | "408" ; Section 10.4.9: Request Time-out | "409" ; Section 10.4.10: Conflict | "410" ; Section 10.4.11: Gone | "411" ; Section 10.4.12: Length Required | "412" ; Section 10.4.13: Precondition Failed | "413" ; Section 10.4.14: Request Entity Too Large | "414" ; Section 10.4.15: Request-URI Too Large | "415" ; Section 10.4.16: Unsupported Media Type | "416" ; Section 10.4.17: Requested range not satisfiable | "417" ; Section 10.4.18: Expectation Failed | "500" ; Section 10.5.1: Internal Server Error | "501" ; Section 10.5.2: Not Implemented | "502" ; Section 10.5.3: Bad Gateway | "503" ; Section 10.5.4: Service Unavailable | "504" ; Section 10.5.5: Gateway Time-out | "505" ; Section 10.5.6: HTTP Version not supported | extension-code
URL Structure
In REST design the URL endpoints should be well formed and should be easily understandable. Every URL for a resource should be uniquely identified. If your API needs an API key to access, the api key should be kept in HTTP headers instead of including it in URL.
For an example:
GET http://abc.com/v1/tasks/11 – Will give the details of a task whose id is 11
POST http://abc.com/v1/tasks – Will create a new task
API Versioning
There is a huge discussion on API versioning whether to maintain api version in the URL or in the HTTP request headers. Even though it is recommended that version should be included in the request headers, I feel comfortable to maintain it in the URL itself as it is very convenient on the client side to migrate from one version to another.
Example:
http://abc.com/v1/tasks
http://abc.com/v2/tasks
Content Type
The Content Type in HTTP headers specifies the kind of the data should be transferred between server and client. Depending upon the data your API supporting you need to set the content type.
For an example, JSON Mime type should be Content-Type: application/json, for XML Content-Type: application/xml. You can find list of supported MIME Types here
Recursos:
rfc2617 : http://tools.ietf.org/html/rfc2617
Fàcil:
$ http -a username:password example.org
Als headers/capçaleres d'una petició HTTP (HTTP REQUEST) hi ha una capçalera que s'utilitza per enviar l'autorització anomenada
Request header Authorization
Exemple:
Authorization: bf45c093e542f057caee68c47787e7d6
És recomanable protegir aquest informació amb SSL i/o tècniques com nonce o digests.
Format:
Authorization = "Authorization" ":" credentials
Per exemple amb l'ús de API Tokens
Authorization = Bearer njd9wng4d0ycwnn3g4d1jm30yig4d27iom5lg4d3
El format de l'autenticació bàsica HTTP (HTTP Basic Authentication) és base64:
$header = "Authorization: Basic " . base64_encode($username . ':' . $password);
ho podeu veure amb httpie
$ http -v http://username:password@localhost:8000/fragments.php?arg=value#anchor GET /fragments.php?arg=value HTTP/1.1 Accept: */* Accept-Encoding: gzip, deflate Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ= Connection: keep-alive Host: localhost:8000 User-Agent: HTTPie/0.9.2
A user agent that wishes to authenticate itself with a server usually, but not necessarily, after receiving a 401 response--does so by including an Authorization request-header field with the request. The Authorization field value consists of credentials containing the authentication information of the user agent for the realm of the resource being requested.
HTTP access authentication is described in "HTTP Authentication: Basic and Digest Access Authentication" [43]. If a request is authenticated and a realm specified, the same credentials SHOULD be valid for all other requests within this realm (assuming that the authentication scheme itself does not require otherwise, such as credentials that vary according to a challenge value or using synchronized clocks).
Recursos:
<?php if (!isset($_SERVER['PHP_AUTH_USER'])) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); echo 'Texte utilisé si le visiteur utilise le bouton d\'annulation'; exit; } else { echo "<p>Bonjour, {$_SERVER['PHP_AUTH_USER']}.</p>"; echo "<p>Votre mot de passe est {$_SERVER['PHP_AUTH_PW']}.</p>"; } ?>
HTTP Digest aka Digest_access_authentication
Digest access authentication is one of the agreed-upon methods a web server can use to negotiate credentials, such as username or password, with a user's web browser. This can be used to confirm the identity of a user before sending sensitive information, such as online banking transaction history. It applies a hash function to a password before sending it over the network, which is safer than basic access authentication, which sends plaintext.
Tècnicament l'autenticació digest utilitza:
Gràfica:
http://upload.wikimedia.org/wikipedia/commons/4/4f/Nonce-cnonce-uml.svg
Vegeu també:
Recursos:
Vegeu API Key
Apache. Consulteu Apache#Autenticaci.C3.B3_Digest.htpasswd
Vegeu httpie
Vegeu curl o Curl_com_a_rest_client
NOTA: S'utilitzen sovint com a una especie de fingerprint o hash d'un recurs HTTP. Permet saber si el recurs ha canviat (té un eTag diferent al anterior) o no per tal de saber si podem o no fer cache
The ETag or entity tag is part of HTTP, the protocol for the World Wide Web. It is one of several mechanisms that HTTP provides for web cache validation, and which allows a client to make conditional requests. This allows caches to be more efficient, and saves bandwidth, as a web server does not need to send a full response if the content has not changed. ETags can also be used for optimistic concurrency control,[1] as a way to help prevent simultaneous updates of a resource from overwriting each other.
An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL. If the resource content at that URL ever changes, a new and different ETag is assigned. Used in this manner ETags are similar to fingerprints, and they can be quickly compared to determine whether two versions of a resource are the same. Comparing ETags only makes sense with respect to one URL—ETags for resources obtained from different URLs may or may not be equal, so no meaning can be inferred from their comparison.
Vegeu Javascript i HTTP
Vegeu HTTP Session
Vegeu HTTP Cookies
Content-negotation a HTTP és el mecanisme que s'utilitza per tal de servir diferents versions d'un mateix recurs (representat normalment per la seva URL). Normalment el user-agent (Navegador) pot, mitjançant l'ús de capçaleres HTTP, negociar amb el servidor quina versió del recurs desitja. És important destacar que la URL del recurs serà la mateixa per a les múltiples versions d'un mateix document.
A cada versió d'un mateix document l'anomenem representation.
La negociació de contingut s'utilitza per exemple en el cas de les API REST per tal de decidir el format de la resposta per exemple decidir entre una resposta en format JSON o XML.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation
Normalment hi ha dos formes/mecanismes d'implementar la negociació de continguts:
Resources:
En aquest cas el user-agent utilitza capçaleres HTTP per indicar les preferències de l'usuari. El servidor utilitza aquesta informació com a pistes/hints per tal de decidir quina representació/versiódel recurs servir al user-agent. El algorisme utilitzat pel servidor no està especificat a l'estàndard HTTP i depèn de cada servidor (vegeu per exemple Apache [1]). Les capçaleres utilitzades per a la negociació de continguts són:
Podem obtenir les capçaleres amb el mètode header del objecte REQUEST:
Route::get('/foo', function() { $accept = request()->header('accept'); // application/json if( $accept === 'application/json' ) { return ['foo' => 'bar']; // Returns JSON, thanks to Laravel Magic™ } return view('foo.bar'); });
En el cas de Json de fet ja tenim un mètode wantsJson:
Laravel provides a nice, easy way to check if a request "wants json":
Route::get('/foo', function() { // Look at this nice, friendly global helper function // Hello, global function! We sincerely love you with all our <3 if( request()->wantsJson() ) { return ['foo' => 'bar']; } return view('foo.bar'); });
public function wantsJson() { $acceptable = $this->getAcceptableContentTypes(); return isset($acceptable[0]) && Str::contains($acceptable[0], ['/json', '+json']); }
HI ha altres mètodes interessant com:
Recursos:
HTTP 1.0: Si el client suporta connexions persistents ho ha d'indicar a la capçalera HTTP amb:
Connection: keep-alive
A partir del protocol HTTP1.1 és el comportament per defecte
https://upload.wikimedia.org/wikipedia/commons/d/d5/HTTP_persistent_connection.svg
Resources:
Vegeu Content Security Policy
Vegeu article HTTP 2