In a REST API, to GET a resource, should I include the resource ID in the url? - rest

I am trying to create an REST API for creating and retrieving files in my database. The tutorial I was following uses the following method to retrive a single file:
$app->get('/file/:file_id', 'authenticate', function($file_id) {
global $user_id;
$response = array();
$db = new DbHandler();
// fetch file
$result = $db->getFile($file_id, $user_id);
if ($result != NULL) {
$response["error"] = false;
$response["id"] = $result["id"];
$response["file"] = $result["fileLocation"];
$response["status"] = $result["status"];
$response["createdAt"] = $result["created_at"];
echoRespnse(200, $response);
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exist";
echoRespnse(404, $response);
}
});
Here they are using the HTTP GET method and are specifying the file ID in the URL, is it OK to do this, safety wise? Would it not be safer to use POST and hide the file ID in the body of the request, or should they not be putting the file ID in a header with the GET request? or is it not something I should be worried about?

In REST post method is used to create a new resource not to get it. Get method is used for fetching the resource and you need to specify the ID to determine particular resource. Passing it via URL is a common practice. You can randomly generate such ID to make it harder to guess.

As Opal said above, the ID is used to identify a resource. If you are unsure have a read of this - http://blog.teamtreehouse.com/the-definitive-guide-to-get-vs-post

Related

Google Analytics Reporting API - Get Activity data via Client ID

I am trying to get user activity data via his client id using Google Analytics api. Take a look at the below image:
Now highlighted text is users client id, it could be user id too, and when I trying to get it via Google's playground, I get the correct response and activity data which is required, like:
and this is the response:
which is required and OK.
but I want this data via API, and have searched the web to get it, but nothing helped me.
Here is sample code Google showing i.e.
function getReport($analytics) {
// Replace with your view ID, for example XXXX.
$VIEW_ID = "<REPLACE_WITH_VIEW_ID>";
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("7daysAgo");
$dateRange->setEndDate("today");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("sessions");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setMetrics(array($sessions));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}
I do found a class for adding user to request i.e.
$user = new Google_Service_AnalyticsReporting_User();
$user->setType("CLIENT_ID");
$user->setUserId("660467279.1539972080");
but this class Google_Service_AnalyticsReporting_ReportRequest which accepts conditions/filters for query does not have such method to accept user object.
How can I achieve this?
You should use this function: $analytics->userActivity->search().
$search = new Google_Service_AnalyticsReporting_SearchUserActivityRequest();
$search->setViewId($VIEW_ID); // Google Analytics View ID
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("7daysAgo");
$dateRange->setEndDate("today");
$search->setDateRange($dateRange);
$user = new Google_Service_AnalyticsReporting_User();
$user->setType("USER_ID"); // or CLIENT_ID if you are not using custom USER ID views
$user->setUserId($user_id); // The actual user's ID as stored in your DB passed to GA
$search->setPageSize(10); // Number of results you want to pull
$search->setUser($user);
return $analytics->userActivity->search($search); // Perform the search query.
Alternatively you can also pass the params to search() like:
$params = [
'metrics' => //Your comma separated desired metrics
'dimmensions' => //Your comma separated custom dimmentions
]
return $analytics->userActivity->search($search, $params);

Retrieving SendGrid Transactional Templates List

I have been trying to retrieve list of SendGrid transactional templates using API. I'm using correct API key and getting an empty array while there are about 5 transactional templates existing in my SendGrid account. Here is the response:
{
"templates": []
}
Any guesses what could be wrong?
Any guesses what could be wrong?
Yep, their documentation could be!
I also stuck with the problem and finally managed to solve it once I opened the devtools and saw how they request their own API from the UI. Long story short - one has to pass additional generations=dynamic query parameter. Here is the C# code I use:
var client = new SendGridClient("key");
var response = await client.RequestAsync(
SendGridClient.Method.GET,
urlPath: "/templates",
queryParams: "{\"generations\": \"dynamic\"}");
Using Api 7.3.0 PHP
require("../../sendgrid-php.php");
$apiKey = getenv('SENDGRID_API_KEY');
$sg = new \SendGrid($apiKey);
#Comma-delimited list specifying which generations of templates to return. Options are legacy, dynamic or legacy,dynamic
$query_params = json_decode('{"generations": "legacy,dynamic"}');
try {
#$response = $sg->client->templates()->get();
$response = $sg->client->templates()->get(null, $query_params);
echo $response->body();
exit;
} catch (Exception $e) {
echo '{"error":"Caught exception: '. $e->getMessage().'"}';
}
I had the same problem using the python wrapper provided by Sendgrid.
My code was similar to this:
response = SendGridAPIClient(<your api key>).client.templates.get({'generations': 'legacy,dynamic'})
This returned an empty array.
To fix you have to name the param or to pass None before the dict:
response = SendGridAPIClient(<your api key>).client.templates.get(None, {'generations': 'legacy,dynamic'})
or
response = SendGridAPIClient(<your api key>).client.templates.get(query_params={'generations': 'legacy,dynamic'})

How to make a REST delete method with cfhttp

I have never done it before and now when the need arise, things are not working.
I have to send an ID to delete a DB record with RESTful service. Here is the code I am trying:
<cfhttp url="http://127.0.0.1:8500/rest/test/something" method="DELETE" port="8500" result="qryRes1">
<cfhttpparam type="body" value="36"/>
</cfhttp>
and in the REST function
remote any function someName() httpmethod="DELETE"{
var testID = ToString(getHTTPRequestData().content);
//make db call to delete
return testid;
}
The result comes as blank [empty string]. I am not able to retrieve the sent value in function. What I am missing?
Edit: one slightly different but related to CF rest, is it necessary to convert query to an array before sending it back to client? Directly serializing won't solve the purpose same way?
you may want to take a look at deleteUser() in http://www.anujgakhar.com/2012/02/20/using-rest-services-in-coldfusion-10/ as an example of how to support DELETE in REST API style.
remote any function deleteUser(numeric userid restargsource="Path") httpmethod="DELETE" restpath="{userid}"
{
var response = "";
var qry = new Query();
var userQry = "";
qry.setSQl("delete from tbluser where id = :userid");
qry.addParam(name="userid", value="#arguments.userid#", cfsqltype="cf_sql_numeric");
userQry = qry.execute().getPrefix();
if(userQry.recordcount)
{
response = "User Deleted";
} else {
throw(type="Restsample.UserNotFoundError", errorCode='404', detail='User not found');
}
return response;
}
As for the 2nd part of your question, it'd be best to first turn a query into a array of structs first unless you're using CF11 which does it for you. See: http://www.raymondcamden.com/index.cfm/2014/5/8/ColdFusion-11s-new-Struct-format-for-JSON-and-how-to-use-it-in-ColdFusion-10
The default JSON structure for query in CF 8 to 10 were designed for <cfgrid> in ColdFusion on top of Adobe's discontinued Spry framework.

AngularJS $resource creating new object instead of updating object

// Set up the $resource
$scope.Users = $resource("http://localhost/users/:id");
// Retrieve the user who has id=1
$scope.user = $scope.Users.get({ id : 1 }); // returns existing user
// Results
{"created_at":"2013-03-03T06:32:30Z","id":1,"name":"testing","updated_at":"2013-03-03T06:32:30Z"}
// Change this user's name
$scope.user.name = "New name";
// Attempt to save the change
$scope.user.$save();
// Results calls POST /users and not PUT /users/1
{"created_at":"2013-03-03T23:25:03Z","id":2,"name":"New name","updated_at":"2013-03-03T23:25:03Z"}
I would expect that this would result in a PUT to /users/1 with the changed attribute. But it's instead POST to /users and it creates a new user (with a new id along with the new name).
Is there something that I'm doing wrong?
AngularJS v1.0.5
you just need to tell the $resource, how he has to bind the route-parameter ":id" with the JSON Object:
$scope.Users = $resource("http://localhost/users/:id",{id:'#id'});
This should work,
regards
thanks for the answer. It worked in the end for me too.
As a side note, I was using .NET WEB API and my entity has an Id property (UPPER CASE "I").
The PUT and DELETE worked only after I used the following:
$scope.Users = $resource("http://localhost/users/:Id",{Id:'#Id'});
Hope it helps.

using Zend_Gdata_Spreadsheets for public spreadsheets?

I have this code which is working, to load a Google Spreadsheet and load some data from it. If the spreadsheet in question is public, how do i modify the code to not require a username/password?
$key="keytothespreadsheet";
$user="test#example.com";
$pass="*****";
$authService = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$httpClient = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $authService);
$gdClient = new Zend_Gdata_Spreadsheets($httpClient);
$query = new Zend_Gdata_Spreadsheets_DocumentQuery();
$query->setSpreadsheetKey($key);
$feed = $gdClient->getWorksheetFeed($query);
print_r($feed);
In the following line, the HTTP client is optional:
$gdClient = new Zend_Gdata_Spreadsheets($httpClient);
So, just don't pass it. The following are equivalent:
$gdClient = new Zend_Gdata_Spreadsheets();
// or
$gdClient = new Zend_Gdata_Spreadsheets(null);
// or
$gdClient = new Zend_Gdata_Spreadsheets(new Zend_Http_Client());
Like #Matt, I wanted to access a public spreadsheet without supplying credentials. Thanks to #Derek Illchuk, I got part of the way there. It still wasn't working, however, until I learned the following:
Note that the File > Publish to the Web feature is not the same thing as Sharing Settings > Public On The Web. If you forget to enable "Publish to the Web", you'll get this error: "Expected response code 200, got 400 The spreadsheet at this URL could not be found. Make sure that you have the right URL and that the owner of the spreadsheet hasn't deleted it."
In the "Publish to the Web" settings, be sure to uncheck "Require viewers to sign in with their ___ account.". Otherwise you'll get this error: "Expected response code 200, got 403 You do not have view access to the spreadsheet. Make sure you are properly authenticated."
According to Google's documentation, "The spreadsheets feed only supports the 'private' visibility and the 'full' projection." However, I found that I needed to specify 'public' visibility and 'basic' projection. Otherwise I got this error:
"Expected response code 200, got 501 Bad or unsupported projection for this type of operation."
Here is what worked for me:
$spreadsheetService = new Zend_Gdata_Spreadsheets(null);
$query = new Zend_Gdata_Spreadsheets_CellQuery();
$query->setSpreadsheetKey($spreadsheetKey);
$query->setWorksheetId($worksheetId);
$query->setVisibility('public'); //options are 'private' or 'public'
$query->setProjection('basic'); //options are 'full' or 'basic'
$cellFeed = $spreadsheetService->getCellFeed($query);
foreach ($cellFeed as $cellEntry) {
$text = $cellEntry->content->text;
//Do something
break; //I only wanted the first cell (R1C1).
}