I am just about to make a webservice available for fellow programmers in my sector using PHP on my own server.
As this is the first time I have done this, I first investigated APIs that I frequently use, Flickr etc.
My service returns granular data extracted from a very large csv file by examining GET arguments, it is read-only.
The data is returned in a variety of formats, xml, json, jsonp etc.
example of the call: /?offices=ABC|XYZ&format=xml
Firstly, I'd like to know if I am I correct in terming my service an "API"?
Also I would also like to know how best to handle failure.
I return straight text messages in the case of a user not submitting the expected input - "you failed to submit any offices".
In the case of any other unforeseen malfunction, at the moment it returns a failure message in payload of the chosen format, eg json with the single array "fail" in it and I have documented this.
Having read up a little on REST recently, when a failure is not caused by misuse of the "API" - should I return something other than HTTP code 200?
If you were accessing this service, what would you prefer to see?
Should I make this another GET option?
e.g /?offices=ABC|XYZ&format=xml&on_failure=http
Or am I getting muddled between the terms API and REST?
SO suggested this post, which deals with 400/401
What's an appropriate HTTP status code to return by a REST API service for a validation failure?
but I am looking for clarification about the terms I am using. If the payload contains the error message - as in the case of Flickr then why should I wander away from that?
The larger providers like Flickr and Twitter have muddied the definition of REST quite a bit. Many developers now mistakenly believe that any service or API over HTTP is "RESTful." What you describe here is more of a data Web service using a form of RPC. Truly RESTful APIs use fluent HTTP and Web standards, and are resource centric.
To answer the main question about HTTP status codes, I would say that for RPC services it's not necessary, as the HTTP status codes won't always directly translate to method call errors. A better approach would be to map your own error codes and return them along with the status message.
For example, an RPC service for user lookups may return the following on success:
SUCCESS=1
USERNAME=example
FIRSTNAME=Example
LASTNAME=User
DISPLAYNAME=Example User
The same service may return the following on failure:
SUCCESS=0
ERRORCODE=1002
ERRORMSG=User subsystem error; requested user was not found.
In an RPC service, the exact details of the response are very flexible. All it does is relay the results of the method call to the invoker. As long as you document what the developer should see, and return clear and consistent messages, it'll work out just fine. The only HTTP status codes an RPC service should return are 200 and 500 (and only then when things break so badly you can't even return a proper error).
Back to the matter of REST, the same user service can be made RESTful if we think of a user as a resource and use an appropriate URL scheme. The very, very basic makeup of a RESTful API are as follows:
GET /api/users - should return a list
of available user accounts in the
system.
GET /api/users/example - should return
details of the example account;
returns a 404 HTTP status if the user
does not exist.
POST /api/users - create a new user
account; should return a link to the
newly created account (ways of doing
this vary, but the LOCATION header
makes sense here). Various HTTP status
codes may be returned depending on the
result.
PUT /api/users/example - edit the
details of an existing user account.
Various HTTP status codes may be
returned depending on the result.
DELETE /api/users/example - delete an
existing user account. Various HTTP
status codes may be returned depending
on the result.
The standard HTTP status codes most common to RESTful interfaces are below.
200 OK - The request was successfully completed. If this request created a new resource that is addressable with a URI, and a response body is returned containing a representation of the new resource, a 200 status will be returned with a Location header containing the canonical URI for the newly created resource.
201 Created - A request that created a new resource was completed, and no response body containing a representation of the new resource is being returned. A Location header containing the canonical URI for the newly created resource should also be returned.
202 Accepted - The request has been accepted for processing, but the processing has not been completed. Per the HTTP/1.1 specification, the returned entity (if any) SHOULD include an indication of the request's current status, and either a pointer to a status monitor or some estimate of when the user can expect the request to be fulfilled.
204 No Content - The server fulfilled the request, but does not need to return a response message body.
400 Bad Request - The request could not be processed because it contains missing or invalid information (such as validation error on an input field, a missing required value, and so on).
401 Unauthorized - The authentication credentials included with this request are missing or invalid.
403 Forbidden - The server recognized your credentials, but you do not possess authorization to perform this request.
404 Not Found - The request specified a URI of a resource that does not exist.
405 Method Not Allowed - The HTTP verb specified in the request (DELETE, GET, HEAD, POST, PUT) is not supported for this request URI.
406 Not Acceptable - The resource identified by this request is not capable of generating a representation corresponding to one of the media types in the Accept header of the request.
409 Conflict - A creation or update request could not be completed, because it would cause a conflict in the current state of the resources supported by the server (for example, an attempt to create a new resource with a unique identifier already assigned to some existing resource).
500 Internal Server Error - The server encountered an unexpected condition which prevented it from fulfilling the request.
501 Not Implemented - The server does not (currently) support the functionality required to fulfill the request.
503 Service Unavailable - The server is currently unable to handle the request due to temporary overloading or maintenance of the server.
Hopefully this information is useful, and not overload. :-)
Related
I have a ProjectStep resource in my application and I have to create an API endpoint that will be used to update my ProjectStep to mark it as finished and create the next ProjectStep. In my REST API I could just do something like this :
PATCH /project-mark/1
POST /project-mark
But I would like to use only one request to update the current step, create a new one and return the newly created ProjectStep.
What method would you use? A PATCH request updating an existing resource and returning a different resource doesn't sound like a good idea.
Thank's
Use a PUT request, please see this link
https://stackoverflow.com/questions/630453/put-vs-post-in-rest
Use PUT APIs primarily to update existing resource (if the resource does not exist then API may decide to create a new resource or not). If a new resource has been created by the PUT API, the origin server MUST inform the user agent via the HTTP response code 201 (Created) response and if an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request.
If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.
I'm writing a web API.
I'm working with an 3rd party client that has sent a application/json request with an invalid JSON body.
My controller never get's the request because Symfony responds with Invalid json message received (400 Bad Request).
The developer of the 3rd party client will need this invalid JSON to debug their software.
Other than changing the content-type to text/plain, then testing the JSON myself, how can I save the invalid JSON for review later?
Thanks!
If you need to log an exception during a request handle, you just need to register an event listener on the kernel.exception. This event dispatches a GetResponseForExceptionEvent where you can find the triggered exception, the request and some others informations.
So, in this listener, check if the exception if a Symfony\Component\HttpKernel\Exception\BadRequestHttpException and then, log the request body where/as you want for further debugging.
Ah, ok. This was programmer error. The check wasn't done by Synfony, but by a leftover Friends Of Symfony Rest module. After removing this module, the behavior disappeared. Controller has to check the JSON body anyways.
Overview
I'm currently working on a jQuery/HTML5 project that displays web performance data with a series of charts using an internal API to retrieve the data. The API is powered by Yii, but I am not working on it, so i cannot change or experiment with it myself.
Basically I am hoping someone can help identify if the API is the root cause of the problem or if it's a problem with the Ajax in my jQuery being incorrect.
A small explanation of the process my application goes through...
Application loads, uses user details to authenticate with API. Receives API Key from API.
After the key has been retrieved, several calls are made to retrieve data from the APi to display as the web performance data.
At set intervals, a generic is called to the database to check that the API Key has expired or not.
If the key has expired, it makes another request to the API for a new API Key as stated in step 1. If there are any problems with gaining an API key, this is when the user gets kicked off.
Restart cycle excluding getting the data.
Problem
All Ajax calls are made to the are crossdomain as both the project and the API are on separate sub domains. These are done using JSONP and a jQuery callback.
The problem I am having is that when I need to authenticate if the key is valid or not, if it is no longer valid, the API returns a 401 error which my Ajax does not register. If i view the API URL in Firefox, I can see the returned Json data, wrapped in a callback, but when I check firebug it says there is a request, but no response.
Basically when the API returns data that is not 200 OK, it doesn't send a response header at all.
However I have manually called the API using cUrl in terminal, and have received a response header, as well as in Google Chrome.
If someone could tell me if this is a well known issue with Firefox/jQuery or if this is a problem with the Yii API I would very much appreciate it.
Try adding this before your ajax call:
jQuery.support.cors = true; // force cross-site scripting in IE
Well, created my personal API server, setted proper response codes, content and cache control(Ex. 404 Not Found, application/json, no-cache, must-revalidate) What else could be setted (in headers) to achieve "perfect" API ?
This API is public, but in future there are plans to create private API for registered user's. Is there any header's "settings" for this kind of API (like Unauthorized, WWW-Authenticate etc.)
You can add a parameter to suppress HTTP codes. Twitter has suppress_response_codes parameter. Quote from dev.twitter.com
suppress_response_codes: If this parameter is present, all responses will be returned with a 200 OK status code - even errors. This parameter exists to accommodate Flash and JavaScript applications running in browsers that intercept all non-200 responses. If used, it’s then the job of the client to determine error states by parsing the response body. Use with caution, as those error messages may change
Here is some resources for good RESTful api design.
Restful API Design
RESTful Service
Mobile API Design - Thinking Beyond REST
Create a REST API with PHP
I need a background process to be an API over a URL.
For example, the url http://www.msite.com/myapi.php will read incoming protocol and reply.
What is the best way to accomplish this scenario?
Should I just treat this as a regular web page?
What are the pros/cons for using a web page url as an API?
You should implement this as REST service. Check this URL out.
You need to create a proper controller (in case you use MVC approach) and implement proper methods corresponding to your API (HTTP request methods are very important topic here).
Just to illustrate, I allowed myself to paste code from URL I embedded here:
GET request to /api/users – List all users
GET request to /api/users/1 – List info for user with ID of 1
POST request to /api/users – Create a new user
PUT request to /api/users/1 – Update user with ID of 1
DELETE request to /api/users/1 – Delete user with ID of 1
Just to notice, you can also use different approach like XML-RPC or SOAP.