How can I have multiple responses from a single endpoint with different parameters? - apiary.io

We are looking at using the API Blueprint. There are cases where we would like one request to return a proper response and another request to return an 'error' response such as a 400 bad request so that other developers can work against the mock API on apiary.io with both types of responses and handle it in their applications.
I've created a completely arbitrary example below,
## Thing [/thing/{id}]
Gets a thing but the thing id must be a prime number!
+ Parameters
+ id (string) ... ID of the thing, a prime number!
+ Model (application/json)
The thing itself.
+ Body
{
"description": "It is green"
}
### Retrieve a Single Gist [GET]
+ Response 200
[Gist][]
Now somehow I would like to add in a response for /thing/40
+ Response 400
{ "error" : "Invalid request" }
But I am not sure how I would do this with the API Blueprint. This was achievable under the 'old' style on apiary.io but we'd like to move on to the new syntax

To document multiple responses simply add it after the Response 200 like so:
## Thing [/thing/{id}]
Gets a thing but the thing id must be a prime number!
+ Parameters
+ id (string) ... ID of the thing, a prime number!
+ Model (application/json)
The thing itself.
+ Body
{
"description": "It is green"
}
### Retrieve a Single Gist [GET]
+ Response 200
[Thing][]
+ Response 400 (application/json)
{ "error" : "Invalid request" }
Note there is currently no dedicated syntax to discuss the conditions (when this response i s returned). You can discuss it anyway you like it for example:
+ Response 400 (application/json)
This response is returned when no `Thing` for given `id` exists.
+ Body
If you are using Apiary mock, keep in mind that the first response listed is returned by default, unless you say otherwise using the prefer HTTP header.

You can use the templates and specify a specific use case after a generic response for your resource, see example:
Reservation [/reservation/{reservation_key}]
A Reservation object has the following attributes:
room_number
reserved_at - An ISO8601 date when the question was published.
booker_details - A Booker Object.
Parameters
reservation_key (required, text, 1) ... Reservation Key ash
View a Reservation Detail [GET]
Response 200 (application/json)
{
"room_number": 55,
"reserved_at": "2014-11-11T08:40:51.620Z",
"booker_details":
{
"name": "Jon",
"last_name": "Doe",
}
}
Reservation [/reservation/notarealreservation123]
Using a non existing reservation (pls use notarealreservation123 in the fake) returns not found

Related

Insomnia - HTTP POST method with request body having an integer

I'm doing a POST method on insomnia with the following payload
{
“tag_ids”: [
295
]
}
I'm receiving a status 400 bad request with the following error message
{
"detail": "JSON parse error - Expecting property name enclosed in double quotes: line 2 column 2 (char 3)"
}
When trying on curl I haven't had any issues and it is working as expected.
I'm wondering if it has something to do with the tag_ids being an integer in the request body, or if there is any settings I should change on the client for this to work.
Thanks
Looks like your json contains “ character instead of " for the property name.
This should be the correct body:
{
"tag_ids": [
295
]
}

How to parametrise a single Cucumber API test Scenario with Multiple Json request in KARATE framework

As of now, I have a single cucumber scenario which runs with a json file with single API request. I want to run the same scenario for multiple API request using same json. So I can verify multiple api test.
#Test1
Feature: Test_Multiple_API_Karate
Scenario: Exe - Individual Rule
* url restBaseApi
* configure headers = read('classpath:headers.js')
* def caseRequest = read('../data/caseRequest.json')
* def caseExpectedResponse = read('../data/caseExpectedResponse.json')
Given path ‘case-Karate-request’
And request caseRequest[i]
When method POST
Then status 200
Then print response
And match response == caseExpectedResponse[i]
We need to run karate request with caseRequest.json (as mentioned below)
[
{
"srId": "1-2A1”,
"process": “Information”,
"area": “Software”,
"subArea": “Technical”,
"status": “Open”
},
{
"srId": “1-2A2”,
"process": “Manufacture”,
"area": “Software”,
"subArea": “SAP”,
"status": “Closed”
}
]
How to run this scenario with the test data for both request in single execution.
please look into the documentation for Data Driven Scenarios
#Test1
Feature: Test_Multiple_API_Karate
Background:
* def caseRequest = read('../data/caseRequest.json')
* def caseExpectedResponse = read('../data/caseExpectedResponse.json')
Scenario Outline: Exe - Individual Rule
* url restBaseApi
* configure headers = read('classpath:headers.js')
Given path ‘case-Karate-request’
And request __row
When method POST
Then status 200
Then print response
And match response == caseExpectedResponse[__num]
Examples:
|caseRequest|
I also suggest you merge both JSON array into the singe JSON to avoid any confusion on index while altering

PUT Request not happening at all in Fantom

I am having some trouble with PUT requests to the google sheets api.
I have this code
spreadsheet_inputer := WebClient(`$google_sheet_URI_cells/R3C6?access_token=$accesstoken`)
xml_test := XDoc{
XElem("entry")
{
addAttr("xmlns","http://www.w3.org/2005/Atom")
addAttr("xmlns:gs","http://schemas.google.com/spreadsheets/2006")
XElem("id") { XText("https://spreadsheets.google.com/feeds/cells/$spreadsheet_id/1/private/full/R3C6?access_token=$accesstoken"), },
XElem("link") { addAttr("rel","edit");addAttr("type","application/atom+xml");addAttr("href","https://spreadsheets.google.com/feeds/cells/$spreadsheet_id/1/private/full/R3C6?access_token=$accesstoken"); },
XElem("gs:cell") { addAttr("row","3");addAttr("col","6");addAttr("inputValue","testing 123"); },
},
}
spreadsheet_inputer.reqHeaders["If-match"] = "*"
spreadsheet_inputer.reqHeaders["Content-Type"] = "application/atom+xml"
spreadsheet_inputer.reqMethod = "PUT"
spreadsheet_inputer.writeReq
spreadsheet_inputer.reqOut.writeXml(xml_test.writeToStr).close
echo(spreadsheet_inputer.resStr)
Right now it returns
sys::IOErr: No input stream for response 0
at the echo statement.
I have all the necessary data (at least i'm pretty sure) and it works here https://developers.google.com/oauthplayground/
Just to note, it does not accurately update the calendars.
EDIT: I had it return the response code and it was a 0, any pointers on what this means from the google sheets api? Or the fantom webclient?
WebClient.resCode is a non-nullable Int so it is 0 by default hence the problem would be either the request not being sent or the response not being read.
As you are obviously writing the request, the problem should the latter. Try calling WebClient.readRes() before resStr.
This readRes()
Read the response status line and response headers. This method may be called after the request has been written via writeReq and reqOut. Once this method completes the response status and headers are available. If there is a response body, it is available for reading via resIn. Throw IOErr if there is a network or protocol error. Return this.
Try this:
echo(spreadsheet_inputer.readRes.resStr)
I suspect the following line will also cause you problems:
spreadsheet_inputer.reqOut.writeXml(xml_test.writeToStr).close
becasue writeXml() escapes the string to be XML safe, whereas you'll want to just print the string. Try this:
spreadsheet_inputer.reqOut.writeChars(xml_test.writeToStr).close

What's the best way to handle a REST API's 'create' response in Backbone.js

I'm using backbone.js to interact with a REST API that, when posting to it to create a new resource, responds with a status of 201, a 'Location' header pointing to the resource's URI, but an empty body.
When I create a new model at the moment, its successful, but the local representation of the model only contains the properties I explicitly set, not any of the properties that would be set on the server (created_date, etc.)
From what I understand, Backbone would update its representation of the model with data in the body, if there were any. But, since there isn't, it doesn't.
So, clearly, I need to use the location in the Location header to update the model, but what's the best way to do this.
My current mindset is that I would have to parse the url from the header, split out the id, set the id for the model, then tell the model to fetch().
This seems really messy. Is there a cleaner way to do it?
I have some influence over the API. Is the best solution to try to get the API author to return the new model as the body of the response (keeping the 201 and the location header as well)?
Thanks!
Sounds like you will have to do a little customization.
Perhaps override the parse method and url method of your model class inherited from
Backbone.Model.
The inherited functions are:
url : function() {
var base = getUrl(this.collection);
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;
},
parse : function(resp) {
return resp;
},
and you could try something like:
parse: function(resp, xhr) {
this._url = xhr.getResponseHeader('location')
return resp
}
url: function() {
return this._url
}
Yes, backbone.js really wants the result of a save (be it PUT or POST) to be a parseable body which can be used to update the model. If, as you say, you have influence over the API, you should see if you can arrange for the content body to contain the resource attributes.
As you point out, its makes little sense to make a second over-the-wire call to fully materialize the model.
It may be that a status code of 200 is more appropriate. Purists may believe that a 201 status code implies only a location is returned and not the entity. Clearly, that doesn't make sense in this case.
With Backbone 0.9.9, I couldn't get the accepted answer to work. The signature of the parse function seems to have changed in an older version, and the xhr object is no longer available in the function signature.
This is an example of what I did, to make it work with Backbone v0.9.9 and jQuery 1.8.3 (using a Deferred Object/Promise), relying on the jqXHR object returned by Backbone.Model.save() :
window.CompanyView = Backbone.View.extend({
// ... omitted other functions...
// Invoked on a form submit
createCompany: function(event) {
event.preventDefault();
// Store a reference to the model for use in the promise
var model = this.model;
// Backbone.Model.save returns a jqXHR object
var xhr = model.save();
xhr.done(function(resp, status, xhr) {
if (!model.get("id") && status == "success" && xhr.status == 201) {
var location = xhr.getResponseHeader("location");
if (location) {
// The REST API sends back a Location header of format http://foo/rest/companys/id
// Split and obtain the last fragment
var fragments = location.split("/");
var id = fragments[fragments.length - 1];
// Set the id attribute of the Backbone model. This also updates the id property
model.set("id", id);
app.navigate('companys/' + model.id, {trigger: true});
}
}
});
}
});
I did not use the success callback that could be specified in the options hash provided to the Backbone.Model.save function, since that callback is invoked before the XHR response is received. That is, it is pointless to store a reference to the jqXHR object and use it in the success callback, since the jqXHR would not contain any response headers (yet) when the callback is invoked.
Another other to solve this would be to write a custom Backbone.sync implementation, but I didn't prefer this approach.

How to construct a REST API that takes an array of id's for the resources

I am building a REST API for my project. The API for getting a given user's INFO is:
api.com/users/[USER-ID]
I would like to also allow the client to pass in a list of user IDs. How can I construct the API so that it is RESTful and takes in a list of user ID's?
If you are passing all your parameters on the URL, then probably comma separated values would be the best choice. Then you would have an URL template like the following:
api.com/users?id=id1,id2,id3,id4,id5
api.com/users?id=id1,id2,id3,id4,id5
api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5
IMO, above calls does not looks RESTful, however these are quick and efficient workaround (y). But length of the URL is limited by webserver, eg tomcat.
RESTful attempt:
POST http://example.com/api/batchtask
[
{
method : "GET",
headers : [..],
url : "/users/id1"
},
{
method : "GET",
headers : [..],
url : "/users/id2"
}
]
Server will reply URI of newly created batchtask resource.
201 Created
Location: "http://example.com/api/batchtask/1254"
Now client can fetch batch response or task progress by polling
GET http://example.com/api/batchtask/1254
This is how others attempted to solve this issue:
Google Drive
Facebook
Microsoft
Subbu Allamaraju
I find another way of doing the same thing by using #PathParam. Here is the code sample.
#GET
#Path("data/xml/{Ids}")
#Produces("application/xml")
public Object getData(#PathParam("zrssIds") String Ids)
{
System.out.println("zrssIds = " + Ids);
//Here you need to use String tokenizer to make the array from the string.
}
Call the service by using following url.
http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76
where
http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76
As much as I prefer this approach:-
api.com/users?id=id1,id2,id3,id4,id5
The correct way is
api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5
or
api.com/users?ids=id1&ids=id2&ids=id3&ids=id4&ids=id5
This is how rack does it. This is how php does it. This is how node does it as well...
There seems to be a few ways to achieve this. I'd like to offer how I solve it:
GET /users/<id>[,id,...]
It does have limitation on the amount of ids that can be specified because of URI-length limits - which I find a good thing as to avoid abuse of the endpoint.
I prefer to use path parameters for IDs and keep querystring params dedicated to filters. It maintains RESTful-ness by ensuring the document responding at the URI can still be considered a resource and could still be cached (although there are some hoops to jump to cache it effectively).
I'm interested in comments in my hunt for the ideal solution to this form :)
You can build a Rest API or a restful project using ASP.NET MVC and return data as a JSON.
An example controller function would be:
public JsonpResult GetUsers(string userIds)
{
var values = JsonConvert.DeserializeObject<List<int>>(userIds);
var users = _userRepository.GetAllUsersByIds(userIds);
var collection = users.Select(user => new { id = user.Id, fullname = user.FirstName +" "+ user.LastName });
var result = new { users = collection };
return this.Jsonp(result);
}
public IQueryable<User> GetAllUsersByIds(List<int> ids)
{
return _db.Users.Where(c=> ids.Contains(c.Id));
}
Then you just call the GetUsers function via a regular AJAX function supplying the array of Ids(in this case I am using jQuery stringify to send the array as string and dematerialize it back in the controller but you can just send the array of ints and receive it as an array of int's in the controller). I've build an entire Restful API using ASP.NET MVC that returns the data as cross domain json and that can be used from any app. That of course if you can use ASP.NET MVC.
function GetUsers()
{
var link = '<%= ResolveUrl("~")%>users?callback=?';
var userIds = [];
$('#multiselect :selected').each(function (i, selected) {
userIds[i] = $(selected).val();
});
$.ajax({
url: link,
traditional: true,
data: { 'userIds': JSON.stringify(userIds) },
dataType: "jsonp",
jsonpCallback: "refreshUsers"
});
}