RESTful services Flashcards
What does REST stand for?
REpresentational State Transfer
HTTP is considered stateless because…?
The request before or after this current request are executed independently and have no knowledge of each other.
A GET command in a GET request is immediately followed by the…
resource location
The ? character in a GET request indicates…
the beginning of the parameters
Parameters in a GET request are seperated by…
The & character
What is the code for an ‘ok’ response for a HTTP request?
200 OK
What is REST?
REST is a software architecture that can be followed while designing systems.
With REST, you should provide every resource with what?
A unique ID (for example a URI).
Within REST architecture, you should link what together?
Resources, establishing relationships between the resources
What kind of methods should be used when implementing REST?
Standard methods - such as HTTP / XML
Resources can have multiple representations - what does this indicate?
Different application states
The communication in REST should use HTTP, what does this imply?
That it should be stateless
What approach is used to separate user interface from data storage?
Client / Server
The client / server interaction is…
Stateless
Servers host what?
Resources
Clients consume what?
Resources
Any information that can be named, can be a…
Resource
A resource has what associated with it?
A URI (identifier)
Any given resource can also have associated what?
Metadata
Such as media-type, last modified time etc
When accessing a resource, the resource identifier along with what is specified?
The action to be performed on the resource
Actions are defined using HTTP what?
Verbs
What does the GET verb do?
Retrieves a resource identified by a URI
What does the POST verb do?
Sends a resource to the server, updates the resource in the location identified by the URI
(Post can be used to update the resource)
What does the PUT verb do?
Sends a resource to the server, to be stored in the location identified by the URI - if the resource already exists, it is modified
(Creates the resource, starts the lifecycle)
What does the DELETE verb do?
Deletes a resource identified by a URI
Ends the life cycle of the resource
What does the HEAD verb do?
Retrieves the metadata of a resource identified by the URI
What PHP function is most suited to sending / retrieving data via http?
curl
How do you init curl?
$client = curl_init($url);
How do you terminate a curl connection?
curl_close($client);
Does the file_get_contents function work with web redirects?
Yes - it will automatically follow redirects, rather than returning the redirect message itself.
What configuration option is required to be on in order to use standard PHP file handling functions to do HTTP requests (such as file_get_contents)?
allow_url_fopen directive must be turned on in the php.ini file
What package might be useful if cURL is not available, and allow_url_fopen is not enabled on the webserver?
HTTP_Request2 - which is a PEAR package. PEAR packages are plain PHP, so as long as I can install a PHP file on the sever, it can be used.
What function do you use to configure curl when it is initialised?
bool curl_setopt(resource $ch, int $option, mixed $value)
What does the option CURLOPT_RETURNTRANSFER do?
When set to true, it tells curl to return the data via the call to curl_exec (i.e. as a string return value)
What function would you use to load a url into a xml format via url?
SimpleXMLElement simplexml_load_file();
What function can you use to load xml from a string (that has perhaps been obtained via curl)?
SimpleXMLElement simplexml_load_string();
What function can you use to build a query string?
string http_build_query();
If you are accessing a site that uses http basic auth, how would you modify your file_get_contents call to pass the username and password?
$url = "http://caino:supercool@www.example.com"; $file = file_get_contents($url);
If you are using basic auth - what curl_options would allow you to pass the password and username to retrieve data?
curl_setopt($c, CURLOPT_USERPWD, ‘caino:superhaxor’);
(Same can be done by using CURLOPT_HTTPHEADER option and using a base64 encoded string to write the header with password and username in it).
How do you configure file_get_contents to not follow redirects?
$options = array('max_redirects' => 1); $context = stream_context_create(array('http' => $options)); $file = file_get_contents($url, false, $context);
What function do you use to create a new context?
stream_context_create()
What is a stream context?
A set of parameters and wrapper specific options which modify or enhance the behavior of a stream.
cURL only follows redirects when?
When CURLOPT_FOLLOWLOCATION is enabled
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
How do you configure the maximum number of redirects for cURL?
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($c, CURLOPT_MAXREDIRS, 4);
How would you write a file from the web to a local file using cURL?
$fh = fopen(“local-copy-of-html-file.html”, “w”) or die($php_errormsg);
$c = curl_init(“http://example.com/filelocation.html”);
curl_setopt($c, CURLOPT_FILE, $fh);
curl_exec($c);
curl_close($c);
How could you get cURL to write to a callback function (i.e. for writing to a database)
curl_setopt($c, CURLOPT_WRITEFUNCTION, array($pageSaver, write));
// Where $pageSaver is an object, and write is the method // it will pass on the curl object and the page data
What is the fundamental unit of REST?
A resource
Resources can be identified by two means, what are they?
URI - (Universal Resource Location) - Location
URN - (Universal Resource Name) - Name
Is a URL a URI?
Yes
Is a URI a URL?
Not necessarily, although it can be.
Why are URN’s different from URL?
URN’s are intended to be unique in both space and time - they should identify a resource in such a way that there is no ambiguity.
Why are URL’s different from URI’s?
URL’s can be URI’s, but a URI doesn’t necessarily have to be a URL. This is because they have different potential syntax.
What is the format of a URN?
urn::
Where nid is the namespace identifier, and nss is the namespace specific string.
Example:
urn:isbn:03432234235
What is the standard format for a REST url?
/version/resource/key
Can you process a REST request from the following URL?
www.cainmartin.net/v1/chickens/20
No - we don’t know what the HTTP method is, therefore we cannot process the request.
Some methods in a REST API must be safe, what is a safe method?
It doesn’t modify the resource (GET is a good example)
Some methods in a REST API must be idempotent, what is an idempotent method?
Calling an idempotent method many times is equivalent to calling it once.
What are the NON-SAFE methods?
POST, DELETE and PUT
What are the idempotent methods?
GET, PUT, DELETE
Which method is neither considered safe, or idempotent?
POST
What HTTP feature is used to indicate status of a request?
HTTP status codes
Which status codes are considered to be success?
The 200’s.
Which status codes are considered to be client errors?
The 400’s
Which status codes indicate further action is required for the server to respond?
The 300’s
What status codes indicate a server error?
The 500’s
Is it okay for a resource to have different representations?
Yes - this is quite normal, i.e. it could be JSON, or XML, or HTML and PDF
What $_SERVER variable is useful for determining where to route a REST request?
$_SERVER[‘REQUEST_METHOD’]
If a client attempts to use a method which is not allowed, which HTTP response should you reply with?
405 - Method not allowed
Do the following urls’ point to different resources?
http: //www.food.com/stuff/brocolli
http: //www.food.com/stuff/Brocolli
Yes - they point to different resources. Technically URL’s are case sensitive. (But most web servers will try to make the server behave like they are case insensitive, so in all likelihood will arrive at the same resource).
HTTP is a request and ….. protocol.
Response
The request and response are handled in a …. HTTP transaction
single
Because some methods are not safe, how do we deal with users being left on a page after a non-safe method, refreshing their browser?
One method is to do a redirect after successfully completing a post / or delete (or whatever safe method). This will redirect to a GET page. The GET may simply retrieve the result of the last unsafe command (i.e. a list of users, or confirmation number)
There is a name given to the practice of redirecting after a post - what is it called?
POST / REDIRECT / GET or PRG.
With a safe method (i.e. GET), there is a benefit to having the query string visible in the URL, what is it?
Users can bookmark the url with the query string embeded within it (which could be a search, or whatever). Because GET is both safe and idempotent, there is no issue with the user refreshing the page.
A full HTTP request message consists of what parts?
[method][url][http version]
[headers]
[body]
What is the most common HTTP version seen in request headers as of today?
1.1 (with 2.0 on the horizon)
What is the only required header in HTTP 1.1?
host
What header could be used to indicate it wants to accept the response in french?
Accept-Language: fr-FR
When a header does appear it must…
obey the standards for that header
What does the Referer header do?
When a user clicks a link - the client can send a link to the referring page in this header
What does the User-Agent header do?
Contains information about the user agent / software making the request. Can often be used to determine which browser is making the request.
What does the Accept header do?
Describes the media types the user-agent is willing to accept, used for content negotiation.
What does the Cookie header do?
Contains cookie information
What does the If-Modified-Since header do?
Will contain a date of when the user-agent last retrieved (and cached) the resource. The server only has to return the entire resource if it has been modified since that time.
Some headers can contain multiple values, how are they separated?
By commas usually
i.e.
Accept-Encoding: gzip,deflate,sdhc
If you see / in an Accept header, what does this indicate?
That the client will ultimately accept any data - and will determine itself how to deal with it.
What parts / components does a http response contain?
[version][status][reason]
[headers]
[body]
Which status codes are considered to be informational?
The 0-100’s.
Which redirect is usually used after a successful POST request to make the client retrieve data using GET? (i.e. after a user successfully logs into a system).
302 - Moved temporarily. The client should continue to use the original URL to obtain the resource
If the server has encountered an error in the syntax of the request, what should it respond with?
400 (bad request)
If a user attempts to access a resource they don’t have permission for, what response should be returned?
403 (forbidden)
If a server is throttling requests due to heavy load - what response should be used to indicate this?
503 (Service Unavailable)
If a user sends a request to create a new user, but forgets to fill in a field, what response should the client receive?
200 OK.
The HTTP response and the clients requirements may be different. The HTTP connection occurred and completed successfully, so it should return 200. However, the response will contain information within it that indicates there was an error. NOTE: This is generally the case for web applications and not for web API’s and web Services.
Web API’s and Web services generally operate closer to…
the HTTP spec than web applications. This is evidenced in how they use HTTP codes - rather than returning 200 OK for a failed attempt to create a user, a web service/api may return 400 (bad request) with information in the body as to what went wrong. This is because the web service is likely returning XML / JSON not intended for direct human interpretation.
A server may include in the response the content type which is known as a ….
a MIME type
What is an ETag (in a response header)?
A header which is related to caching / performance optimization. It is an identifier that will change when the underlying resource changes. Therefore comparing ETags is an efficient way of determining when a cached resource has become stale.
What does the ‘Connection: close’ header indicate?
That the connection to the server may not be persistent. Typical with inexpensive hosts like goDaddy.
A forward proxy is closer to…
the client - and the client may require some configuration to use it.
A reverse client is closer to…
the host - and is invisible to the client.
In HTTP 1.1, can a response with a 200 OK header be cached?
Yes
What headers control how caching may be done?
Cache-control
Expires (although this is deprecated, still used)
What are the possible values of Cache-control header?
public - public proxy can cache it
private - only users browser can cache it
no-cache - no one can cache it
no-store - no caching, and also should store the data as it has sensitive information
max-age - gives a time to expire
With HTTP, what are some options with storing state, given HTTP is a stateless protocol?
You can store state in hidden fields to be sent with the next request - good for short lived state tracking, like form filling progress.
You can store state on the server - PHP sessions.
What is the ‘fat url’ technique of tracking a user?
When cookies are not available, the server may write an identifier into the url (cookieless session essentially).
What does the HttpOnly flag do (as part of the set-cookie header)
Prevents JavaScript from modifying cookie data - useful to prevent XSS attacks.
Why do cookies potentially interfere with caching?
Because cookies can be used to identify users, there could be security risks related to caching a cookie - therefore they should not be cached. So any response with a Set-Cookie header should not be cached (at the very least, not the headers).
In HTTPS what is encrypted?
Everything after the host name in the url, and all request and response traffic (including headers and body).
When we send a request to a server, the server usually responds with a document, this document is called a…
representation of the resource
The concept of addressability says that every resource should have…
it’s own url
In REST terms, the page that you are on represents the…
application state
What is HATEOAS?
Acronym for - Hypermedia As The Engine Of Application State
Basically refers to ‘which page you are on’
The value of the content-type header is known as the …….. of the body.
media type (or MIME type)
JSON must be served as… (what content-type)?
application/json
If you receive a content type of “application/vnd.collection+json”, is it just JSON?
No - JSON is served using “application/json” - this indicates that it’s a collection+json, which is a standard for publishing searchable list of resources over the web.
If you have a content type collection+json, what formatting is required?
It must be a JSON object, and have an element called ‘collection’.
{ “collection”: { “items”: [{}, {}, {}]}}
The items within the item field must also be objects.
The collection+json standard requires a href field - what does that href point to?
The address used to retrieve a representation of the document.
What element of a collection+json document instructs the client as to how to build a message?
The template section
In REST, a representation should describe…
A resources state
What are two methods by which an API can provide multiple representations of the same content (i.e. a JSON format and an XML format)?
Client negotiation - i.e. the client uses the HTTP headers to distinguish amongst representations.
The second is to give the resource multiple urls, one for each representation.
If I send a http DELETE request, and I receive a 204 - no content reply, what does this mean?
The object was deleted, and the server has nothing more to say about it.
If I send a http DELETE request and I receive a 200 OK reply, what does this mean?
The object was deleted, but the server wants to give you further information about it.