How to implement 'fields' paramenter for 'get' in REST API in server side - api

I would like to know, how to implement 'fields' paramenter for 'get' in REST API in server side.
for eg: http://example.com/user?fields=firstName,lastName
Here I have to get the firstName and lastName from users table.
Should I name the table fields like firstName, lastName and select all colums in the fields list or use aliases and find the column names from the aliases and select them?
I also have some secure fields like passwordHash, which should not be requested. So I need to put some restrictions also. So in server side I have to manually check for these fields (also the * or users.* etc). But these fields should be allowed for update.
Can anybody tell me the best approach for implementing this in terms of security, performance and clean code?

Guessing you have an usual web application, you could use a request without any query parameters for all requests and show/hide the columns on the client. You may return too much data on the first request but you don't need additional requests because all the data is there already.
Edit: Of course you should not include "passwordHash" or other sensible data in your query.

Related

REST based URL for complex resource identifier

I am trying to construct URL for the REST API that needs to use complex resource identifier
e.g. Get specific Course
GET /Courses/{id}
where {id} = {TermId}/{SubjectId}/{SectionID}
Is it acceptable to format it as below or there is a better way?
/Courses/{TermId}/{SubjectId}/{SectionID}
It's rather not acceptable, because it introduces confusion to the clients that use the API you provided. Basically / (slash) indicates a new resource. In this particular case you have Courses resources which has a particular resource with TermId which in turn has SubjectId and so on. This is not readable and not what client expects. I see two possible solutions here:
Use combined key, separated with - or other URI-useable sign:
GET /Courses/{TermId}-{SubjectId}-{SectionID}
Just parse such key on the server side.
Use other URI
GET /Courses/{courseId}/Terms/{termId}/subjects/{subjectId}/sections/{sectionId}
There are also other ideas, the one you suggested doesn't seem useable.
As I see it, you have two reasonable options:
Use a compound key, as #Opal said
Use a surrogate key (an arbitrary key with no relation to your three unique constraints)
The advantage to (1) is that the URI is human-hackable - assuming that the user remembers the order to put the values in and what valid values can be. If a significant use case is going to be students using these URIs to find courses online they might like to skip the search step if they have all the relevant information and just punch those values into the URI. If your response type is HTML, this is not unreasonable.
The advantage to (2) is that it's not human-hackable - REST is about discovery through hypermedia. If the response type is JSON or XML, humans aren't going to be using these URIs directly.
I would suggest supporting the following endpoints:
GET /courses?termId={}&subjectId={}&sectionId={}
// all three parameters are optional. returns all courses that match the
// specified criteria - either a subset of the data or the full course
// data for each result
GET /courses/{courseId}

RESTful API - URI Structure Advice

I have REST API URL structure similar to:
/api/contacts GET Returns an array of contacts
/api/contacts/:id GET Returns the contact with id of :id
/api/contacts POST Adds a new contact and return it with an id added
/api/contacts/:id PUT Updates the contact with id of :id
/api/contacts/:id PATCH Partially updates the contact with id of :id
/api/contacts/:id DELETE Deletes the contact with id of :id
My question is about:
/api/contacts/:id GET
Suppose that in addition to fetching the contact by ID, I also want to fetch it by an unique alias.
What should be URI structure be if I want to be able to fetch contact by either ID or Alias?
If you're alias's are not numeric i would suggest using the same URI structure and figuring out if it's an ID or an alias on your end. Just like Facebook does with username and user_id. facebook.com/user_id or facebook.com/username.
Another approach would be to have the client use GET /contacts with some extra GET parameters as filters to first search for a contact and then looking up the ID from that response.
Last option i think would be to use a structure like GET /contacts/alias/:alias. But this would kinda imply that alias is a subresource of contacts.
The path and query part of IRIs are up to you. The path is for hierarchical data, like api/version/module/collection/item/property, the query is for non-hierarchical data, like ?display-fields="id,name,etc..." or ?search="brown teddy bear"&offset=125&count=25, etc...
What you have to keep in mind, that you are working with resources and not operations. So the IRIs are resource identifiers, like DELETE /something, and not operation identifiers, like POST /something/delete. You don't have to follow any structure by IRIs, so for example you could use simply POST /dashuif328rgfiwa. The server would understand, but it would be much harder to write a router for this kind of IRIs, that's why we use nice IRIs.
What is important that a single IRI always belongs only to a single resource. So you cannot read cat properties with GET /cats/123 and write dog properties with PUT /cats/123. What ppl usually don't understand, that a single resource can have multiple IRIs, so for example /cats/123, /cats/name:kitty, /users/123/cats/kitty, cats/123?fields="id,name", etc... can belong to the same resource. Or if you want to give an IRI to a thing (the living cat, not the document which describes it), then you can use /cats/123#thing or /users/123#kitty, etc... You usually do that in RDF documents.
What should be URI structure be if I want to be able to fetch contact
by either ID or Alias?
It can be /api/contacts/name:{name} for example /api/contacts/name:John, since it is clearly hierarchical. Or you can check if the param contains numeric or string in the /api/contacts/{param}.
You can use the query too, but I don't recommend that. For example the following IRI can have 2 separate meanings: /api/contacts?name="John". You want to list every contact with name John, or you want one exact contact. So you have to make some conventions about this kind of requests in the router of your server side application.
I would consider adding a "search" resource when you are trying to resolve a resource with the alias:
GET /api/contacts/:id
and
GET /api/contacts?alias=:alias
or
GET /api/contacts/search?q=:alias
First of all, the 'ID' in the URL doesn't have to be a numerical ID generated by your database. You could use any piece of data (including the alias) in the URL, as long as its unique. Of course, if you are using numerical ID's everywhere, it is more consistent to do the same in your contacts API. But you could choose to use the aliases instead of numeric IDs (as long as they are always unique).
Another approach would be, as Stromgren suggested, to allow both numeric IDs and aliases in the URL:
/api/contacts/123
/api/contacts/foobar
But this can obviously cause problems if aliases can be numeric, because then you wouldn't have any way to differentiate between an ID and a (numeric) alias.
Last but not least, you can implement a way of filtering the complete collection, as shlomi33 already suggested. I wouldn't introduce a search resource, as that isn't really RESTful, so I'd go for the other solution instead:
/api/contacts?alias=foobar
Which should return all contacts with foobar as alias. Since the alias should be unique, this will return 1 or 0 results.

Asterisk Realtime and External SIP table

I'm having spleepless night thanks to Asterisk Realtime.
I have some trouble understanding the documentation ( like http://www.voip-info.org/wiki/view/Asterisk+RealTime+Sip ). Too many tables, many parameters, fragmented informations, no exhaustive tutorial.
I have simply to auto-register some users from an external MySQL's table ( id, user, chatkey ).
Which are the columns i HAVE to set to get it work? If there where simply a user and password column, I would have matched them with my.user and my.chatkey, but now I'm very confused.
Is there any side effects using VIEWS instead table + triggers?
You have set ALL columns. Minimum set is something like type,username, host,name,nat,allow,disallow.
You can do it using mysql view from your current tables.But if you do so, you have use cache of realtime friends or organize contact update(update&store of all fields below&including ipaddr). Otherwise your setup will not able determine where your sip devices.
I don't understand your issues. Wiki is very clear. For sip auth you need only one table sip_buddies
and need put in /etc/asterisk/extconfig.conf
sipusers => mysql,general,sip_buddies
sippeers => mysql,general,sip_buddies
note, general - name of already setuped(in /etc/asterisk/res_mysql.conf) database connection.
From your question i see you not understanding asterisk internals, so i recommending you read Orely's book "Asterisk the future of telephony" or hire expert. Otherwise resulting application will be not scalable and probably will work strange.

REST API naming convention

Given this URI:
/myapp/books/status/{status}
For example :
/myapp/books/status/new
This will return all books flagged with this status.
What would be a proper URI for return all books NOT flagged with a specific status?
/myapp/books/notstatus/new
I would like to return a collection of all books except the ones with a certain status..
Please advice...
I'd recommend using query parameters for filtering status for your books list resource:
myapp/books/?status=new
myapp/books/?status=not_new
Both queries return the same resource (a list of books), you're just filtering out the types you want in that list, so the use of a query param makes sense. I use the not_ prefixed to the status to do inverse queries, but you can use whatever convention you want.
REST doesn't require you to avoid get parameters (it seems some people think get parameters are voodoo), just don't use them to make faux-RPC calls :)
The reason I like this method is it opens up your options later when you might want to add a check for all books with multiple pieces of info such as ones that have a status of new and condition of good.
myapp/books/?status=new&condition=good
If you try to break that down into url segments instead of query params, it gets messy very quickly.
As I know there are a couple of ways, and all of them are correct (from REST perspective):
Query string parameters
myapp/books?status=new
OData queries
http://www.odata.org/documentation/uri-conventions
myapp/books?$filter=status eq 'new'
In URI, also good
myapp/books/status/{status}
Personally I prefer either Query string or OData.
OData is especially good when technology specific (ASP.NET Web API, WCF Data services, by non-Microsofts should also be equivalents) helps to avoid writing any code for such queries.
It allows to expose prefiltered collection and then filter it from client with such query. In such scenarios when exposing collections, I'm using OData queries.

Android Notepad Uri Explanation

In the android Notes demo, it accepts the URI:
sUriMatcher.addURI(NotePad.AUTHORITY, "notes", NOTES);
sUriMatcher.addURI(NotePad.AUTHORITY, "notes/#", NOTE_ID);
Where the difference between notes and notes/# is that notes/# returns the note who's ID matches #.
However, the managedQuery() method that is used to get data from the content provider has the following parameters:
Parameters
uri The URI of the content provider to query.
projection List of columns to return.
selection SQL WHERE clause.
selectionArgs The arguments to selection, if any ?s are pesent
sortOrder SQL ORDER BY clause.
So, is there any particular cause for the design decision of providing a URI for that, rather than just using the selection parameter? Or is it just a matter of taste?
Thank you.
I thinks its so you can do more complex lookups without having to complicate your selections and arguments. For example in my project I have multiple tables but use the same selection and arguments. To filter content. By using the URI I don't have interpret the query, I can just switch on the URI. It.might be personal taste to begin with. But in more complex scenarios you appreciate the URI. You can also use * to match strings in the same.way you can with#.
I think it's mostly a matter of taste. IMHO, putting the id in the Uri is a little cleaner since you can make the id opaque rather than require the client to know that it actually represents a specific row id. For instance, you can pass a lookup key (like in the the Contacts API) rather than a specific row id.