RESTful API - How do I return different results for the same resource? - api

Question
How do I return different results for the same resource?
Details
I have been searching for some time now about the proper way to build a RESTful API. Tons of great information out there. Now I am actually trying to apply this to my website and have run into a few snags. I found a few suggestions that said to base the resources on your database as a starting point, considering your database should be structured decently. Here is my scenario:
My Site:
Here is a little information about my website and the purpose of the API
We are creating a site that allows people to play games. The API is supposed to allow other developers to build their own games and use our backend to collect user information and store it.
Scenario 1:
We have a players database that stores all player data. A developer needs to select this data based on either a user_id (person who owns the player data) or a game_id (the game that collected the data).
Resource
http://site.com/api/players
Issue:
If the developer calls my resource using GET they will receive a list of players. Since there are multiple developers using this system they must specify some ID by which to select all the players. This is where I find a problem. I want the developer to be able to specify two kinds of ID's. They can select all players by user_id or by game_id.
How do you handle this?
Do I need two separate resources?

Lets say you have a controller name 'Players', then you'll have 2 methods:
function user_get(){
//get id from request and do something
}
function game_get(){
//get id from request and do something
}
now the url will look like: http://site.com/api/players/user/333, http://site.com/api/players/game/333
player is the controller.
user/game are the action
If you use phil sturgeon's framework, you'll do that but the url will look like:
http://site.com/api/players/user/id/333, http://site.com/api/players/game/id/333
and then you get the id using : $this->get('id');

You can limit the results by specifying querystring parameters, i.e:
http://site.com/api/players?id=123
http://site.com/api/players?name=Paolo

use phil's REST Server library: https://github.com/philsturgeon/codeigniter-restserver
I use this library in a product environment using oauth, and api key generation. You would create a api controller, and define methods for each of the requests you want. In my case i created an entirely seperate codeigniter instance and just wrote my models as i needed them.
You can also use this REST library to insert data, its all in his documentation..
Here is a video Phil threw together on the basics back in 2011..
http://philsturgeon.co.uk/blog/2011/03/video-set-up-a-rest-api-with-codeigniter
It should go noted, that RESTful URLs mean using plural/singular wording e.g; player = singular, players = all or more than one, games|game etc..
this will allow you to do things like this in your controller
//users method_get is the http req type.. you could use post, or put as well.
public function players_get(){
//query db for players, pass back data
}
Your API Request URL would be something like:
http://api.example.com/players/format/[csv|json|xml|html|php]
this would return a json object of all the users based on your query in your model.
OR
public function player_get($id = false, $game = false){
//if $game_id isset, search by game_id
//query db for a specific player, pass back data
}
Your API Request URL would be something like:
http://api.example.com/player/game/1/format/[csv|json|xml|html|php]
OR
public function playerGames_get($id){
//query db for a specific players games based on $userid
}
Your API Request URL would be something like:
http://api.example.com/playerGames/1/format/[csv|json|xml|html|php]

Related

api platform - Create post requests with nested resources

I'm new to symfony and the api platform and I want to develop an api with specific routes.
I'm looking to do is create a post query with nested resources to add relationships between tables.
example: I have 3 tables (users, periods, articles). I need to create a post request to add a new post with the following structure:
URL: api/:userid/:period/item
:userID = user ID
:period = Period name
name = element name
This request must create a new article in my "articles" table by adding the identifier, the name of the period and the name of the article entered as a parameter.
So my question is how do I pass multiple parameters in my path and save them in the database using the api platform?
Thanks in advance !
You can use custom routes with API platform, which allow you to create a route that correspond to a custom query => but you need to have these data before setting them in your Api platform path.
First of all, I would use the query builder to create the query you need get the data you need, then you can use your method directly in your entity (more here https://api-platform.com/docs/core/controllers/).
You can set the route you want inside of the path of the route and set the different arguments you need like this:
'path' => '/books/{id}/publication'
here id is your argument coming from your repository function.

API formation for side loading only required associated data to ember data

Please check my previous question
EMBER JS - Fetch associated model data from back-end only when required
Related to the above question I need help on API formation in ruby on rails(JSON format: jsonapi.org)
how to form the API for sideloading only students.records and link with data already available in ember-data store (school and students)
based on the comments in the other question, I think you're wanting something like
GET /api/students?include=records
But you need that filtered to a school, which is where application-specific code can come in, as { json:api } does not dictate how filtering should happen
but, I've used this: https://github.com/activerecord-hackery/ransack with much success
So, your new query would be something like:
GET /api/students?include=records&q[school_id_eq]=1
to get all students and their records for the school with id 1
and then to make this query in ember:
store.query('student', {
include: 'records',
q: {
['school_id_eq']: 1
}
});
hope this helps

Can we extract all Visitor ID's from Adobe Analytics using API

I'm looking to determine whether it's possible via visitor API to be able to find out all visitor ID's.
In the code examples below, [your mcorgid here] is your company's marketing cloud organization id. If you do not know this then you need to contact Adobe Client Care to get it.
getMarketingCloudVisitorID - Get the Marketing Cloud Visitor ID (mid= param)
var visitor = Visitor.getInstance("[your mcorgid here]#AdobeOrg")
var mcvid = visitor.getMarketingCloudVisitorID();
getAnalytcisVisitorID - get legacy visitor id (aid= if applicable)
var visitor = Visitor.getInstance("[your mcorgid here]#AdobeOrg")
var aid = visitor.getAnalyticsVisitorID();
getCustomerIDs - get all customer IDs
var visitor = Visitor.getInstance("[your mcorgid here]#AdobeOrg");
var customerIDs = visitor.getCustomerIDs();
s_fid - Fallback ID
There is no built-in method for retrieving this, but you can use AA's s.c_r() cookie reading utility function, or any other cookie reading method you have to look for the s_fid cookie. (sidenote: I do not recommend using DTM's _satellite.readCookie()method. It only looks for cookies on the current page's full (not root) domain, and there is no way to change that. Since AA and most other things usually set on root domain, it makes _satellite.readCookie() unreliable in practice).
var fid = s.c_r('s_fid');
Use Adobe datawarehouse and extract Experience Cloud ID. Assuming you know how to use the API already, here is an easy report to try
report_definition = ReportDefinition(
dimensions="marketingcloudvisitorid",
metrics="visits",
date_from=insertdate,
date_to=insertdate,
source="warehouse"
)

how to do pagination in RESTFUL API in a effective way?

I want to support pagination in my RESTful API.
My API method should return a JSON list of product via http://localhost/products/v1/getproductsbycategory, there are potentially thousands of products, and I want to page through them, so my request should look something like this:
public function getProductsByCategory($product_id,$page){
$perPage=5;
$start=($page-1)*$perPage;
$stmt=$this->conn->prepare("SELECT id,product,description,destination_url,expiry_type,savings,expiry,title,last_updated_on FROM products WHERE product_id=? ORDER BY last_updted_on DESC LIMIT $start ,$perPage");
$stmt->bind_param('i',$category_id);
$stmt->execute();
$productbycategory=$stmt->get_result();
$stmt->close();
return $productbycategory;
}
}
Firstly, in a RESTful call, the URL should ideally be noun-based and not verbs. We are using HTTP verbs (GET, PUT, POST, etc) to do an action on a noun - product in your case.
So, the URL should be http://localhost/products/v1/category
This effectively means you are GETting product of type v1 based on category. To get a given page number, simply add it as a query parameter -
http://localhost/products/v1/category?page=1
and handle it accordingly in your GET implementation corresponding to localhost/products/v1/category
Hope this helps.
Pagination has nothing to do with the JSON format per se - it's all about the query string in the URL and how the server interprets that.
Expanding on #Sampada's answer, you can have a URL like
http://localhost/products/v1/category?pageSize=5&pageNumber=2
and then you'll simply pick the corresponding elements on the server side (consider whether you'll want 0 or 1-based index for the pageNumber), and return them.
Additionally you can wrap this collection in an object that also provides links as to navigate to the previous/next/specific page - see HATEOAS & Richardson's Maturity Model level 3.

CodeIgniter Rest API (Phil Sturgeon) - How to chop up a very large api file

I have been building a rest api (using Phil Sturgeons Codeigniter-Restserver) and Ive been sticking closely to the tutorial at:
http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/
in particular Ive been paying attention to this part of the tutorial:
function user_get()
{
// respond with information about a user
}
function user_put()
{
// create a new user and respond with a status/errors
}
function user_post()
{
// update an existing user and respond with a status/errors
}
function user_delete()
{
// delete a user and respond with a status/errors
}
and Ive been writing the above functions for each database object that is accessible by the api, and also:
function users_get() // <-- Note the "S" at the end of "user"
{
// respond with information about all users
}
I currently have approximately 30 database objects (users, products, clients, transactions etc), all of which have the above functions written for them, and all functions are dumped into /controllers/api/api.php, and this file has now grown to be quite large (over 2000 lines of code).
QUESTION 1:
Is there a way to split this api file up, into 30 files for example, and keep all api functions relating to a single database object in a single place, rather than just dumping all api functions into a single file?
QUESTION 2:
I would also like to keep a separation between my current model functions (non-api related functions) and the functions that are used by the api.
Should I be doing this?
Is there a recommended approach that I should use here? For example should I write separate models that are used by the api, or is ok to keep all model functions (both non-api functions, and api functions) for a given database object in the same file?
Any feedback or advice would be great..
You can create api controllers the same way you do regular controllers; you can do the same with models.
application/controllers/api/users.php
class Users extends REST_Controller{
function user_post(){
$this->users_model->new_user()
...
POST index.php/api/user
--
application/controllers/api/transactions.php
class Transactions extends REST_Controller{
function transaction_get(){
$this->transactions_model->get()
...
GET index.php/api/transaction
I would also like to keep a separation between my current model functions (non-api related functions) and the functions that are used by the api.
I don't see why you couldn't use the same methods so long as they return what you need.