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
Related
I am new to api development, my client required to check or restrict the api call from valid sources
api will throw an error when requested from the postman or other like took in the production. Looking for a solution in laravel 6.*
You can check:
UserAgent Header in the request & allow certain user-agent as per your choice.
You can check the refer header field to identify the the domain from where the endpoint request is made..
You should first define valid sources.
There is various way to restrict your api call like -
From where api should be called from web, api-postman, etc.
From which IP address. You can limit the api call from one IP address using throttle middleware. (for security purpose)
You can put encryption on your api call so that only your application can call that API.
You should always use Authorization on API to secure api response.
Always use Server Side Validation on every api just like you do in your POST or GET request.
I've been trying to implement a private API for a project of mine and I'm looking for some clarity on exactly what method (and even programming language) I should be using to create this implementation. The API was written in PHP, I believe.
The documentation states that I need an authentication token to make all API calls. In order to do that, I've been given a username and password, but I need to send it in "JSON in the body of the HTTP Message"
This is what the documentation states:
All communications will be made using JSON over HTTP. This is a
RESTful API, meaning that it uses a combination of HTTP "verbs" (in
this case GET and PUT) and a URL that indicates the object(s) to be
fetched or acted upon. The parameters should be encoded in JSON in the
body of the HTTP message.
I'm using Postman to test the API and I can only figure out how to send authentication in the headers (I've tried using basic auth and even oAuth).
Can anyone help me shed some light on this? I've done a bit a research and I'm now a bit more lost. Any link to an example on how to do this or any help would be greatly appreciated.
I'm using Postman to test the API and I can only figure out how to send authentication in the headers (I've tried using basic auth and even oAuth).
As you are using postman, in the body tab of the request, select raw type to be JSON(applicatin/json)
Then enter your username and password in the json format.
You can change the http verb near the url parameter to GET, POST, PUT, DELETE or more
The parameters should be encoded in JSON in the body of the HTTP message.
Here is the sample request screenshot to send username and password in body parameter of request. I am using POST type of request here. You have to use the verb that the documentation states.
As stated in comment and documentation that you shared, try using adding those username and password in params. Here is sample screenshot of the request in Postman.
I have developed a website with my friend. For the front-end we are using AngularJS, and for the backend we're using Laravel.
Whenever data has to be fetched, an API call is made from front-end to PHP.
My concern is that this API call is clearly visible in network panel. Then some bad guy can easily abuse this API. How can I avoid this?
In most cases exposing your API is not bad thing, but you need to think about this:
1. You should design your API, so only legitimate operations can be made. In example: person shouldn't be able to delete whole database using API.
2. You could provide some authentication mechanism if needed, so the person trying to call your API will have to be logged in (authentication token should be stored in session and verified in server-side with every API call).
If you want to hide POST/GET Params form console. Try to make JSONP call in angular . JSONP calls are not real ajax requests and won't be shown in Firebug. You can also clear the console using clearconsole() after you receive the response and you can also authenticate the requesting IP in your laravel backend.
It's just like regular routing. For example: Everybody knows that they can access a user's profile on Facebook on the /:username route, but Facebook prevents unauthorized clients from viewing that data. The same concept is used for REST routes.
Just like regular page requests, AJAX calls and the data passed / received can be seen by the user. JSONP can be used to prevent the API requests from being logged by regular developer tools, but that is not a good security solution your API can still be discerned by a malicious user.
Even if you encrypt the request payload and the response, it can be intercepted by a malicious user before encryption and after decryption.
You mentioned using proper authentication on your API, which is usually good enough for most cases.
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
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. :-)