REST API Parameter precedence - api

I'm working on creating a REST API. Lets say the resource I'm serving is called object and it contains a number of properties.
Apart from requesting the entire set of objects like this
GET api.example.com/objects
I want to allow requesting a single object by providing either the objectid or objectname,
like this
GET api.example.com/objects?objectid=
GET api.example.com/objects?objectname=
What I'm confused about is, how should I handle a request like this?
GET api.example.com/objects?objectid=x&objectname=y
In this case, should I return a 400 Bad Request, or should one of the parameters take precedence over the other? How does REST define this behavior?

REST generally assumes there is a unique URL for a resource, so it would be:
GET api.example.com/objects/objectId
Parameters are commonly used for searching, so you would have something like:
GET api.example.com/objects?objectName=x

A better approach would be use a generic key in the parameter string to retrieve field values of your specific resource
GET api.example.com/objects/objectId?field=objectName,anotherField
It complements xpapad's suggestion, and can add scalable structure in how you define a consistent approach to your API design.

Related

REST API design: param value starts with

I need an REST API endpoint which will return all the records having name starting with ABC.
The SQL query would be something like:
SELECT * FROM MyResource WHERE Name LIKE 'ABC%'
But how should I define the query string in the REST endpoint?
Using equal sign in the query string would not be appropriate, I think.
{Base URL}/myresource?name=ABC
Sofar I found following specification that can be used as base for the definition of the query: https://datatracker.ietf.org/doc/html/draft-ietf-scim-api-12#section-3.2.2.2
Equals is fine provided you use correct naming. For this request you can define i.e. 'namePrefix' parameter that is self-descriptive.
But how should I define the query string in the REST endpoint? Using equal sign in the query string would not be appropriate, I think.
Using an equal sign in the query string is fine -- the world wide web has been catastrophically successful, and you'll find query strings with encoded key/value pairs being used for all sorts of things.
There's no particular reason to assume that the spelling of a resource identifier should necessarily match the internal implementation details -- in fact, the opposite is the case: we're supposed to be able to change how a resource is implemented without necessarily needing to introduce a new identifier.
There's a tremendous advantage to using application/x-www-form-urlencoded data as your query string: that's how HTML GET forms do it, which in turn means that pretty much everyone has access to at least one general purpose library that knows how to construct resource identifiers that use that convention.
But if you would rather forego that advantage in favor of some other concern, that's OK too; REST/HTTP don't care what spelling conventions you use for your resource identifiers, so long as the result is consistent with the production rules described in RFC 3986.

How do you write a test for dynamic API content?

I am working on a wrapper for an API, and one of the endpoints returns data that doesn't have the same results each time.
What is a good strategy to test that the endpoint is still valid?
This is a general question, although I am mostly interested in getting this to work in Python.
You need to define what you actually expect from the result. What are the statements that always hold for the result?
Popular candidates/examples are
it is valid JSON/HTML/XML
it contains certain substrings
it has certain "fields"
certain fields can be parsed as a date using a specific format, and the resulting date is within +/-1h of now.

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}

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.

Sparql Query Results without Namespace

I want to get results from sparql query and the results contain no namespace.
ex: there is result in triple format like:
"http://www.xyz.com#Raxit" "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" "http://www.xyz.com#Name"
So i want to get only following:
Raxit type Name
I want to get this results directly from sparql query. I am using virtuoso.
Is it possible to get this from sparql?
Please share your thoughts regarding this.
Thanks in Advance.
If your data is regular, and you know that the sub-string you want always occurs after a # character, then you can use the strafter function from SPARQL 1.1. I do not know whether this is available in Virtuoso's implementation or not.
However this is, in general, a very risky strategy. Not all URI's are formatted with a local name part after a # character. In fact, in general, a URI may not have a legal or useful localname at all. So you should ask yourself: why do you think you need this? Generally speaking, a semantic web application uses the whole URI as an indivisible identifier. If your need is actually for something human-friendly to display in a UI, have your query also look for rdfs:label or skos:label properties. Worst case, try to abbreviate the URI to q-name form (i.e. prefix:name), using the prefixes from the model or a service like prefix.cc
The simplest way to achieve this is to not bother with adapting your query, but to just post-process the result yourself. Depending on which client library you use to communicate with Virtuoso, you will typically find it has API support to parse the result, get back values, and for each value then get only local name (I suggest you look for a URI.getLocalName() method or something similar).