Alamofire formatting POST/PUT parameters swift - swift

I have an issue using Alamofire on iOS (swift) :
When I try to send a request (in .POST or .PUT) with parameters like that :
parameters:["description": WhoGives, "images": (
{
container = offerImages;
name = "563f993e4b00ddad7ed42790_0.jpg";
},
{
container = offerImages;
name = "563f993e4b00ddad7ed42790_1.jpg";
}
)]
it results in a httpBody like this :
description="WhoGives"&images[][container]=“offerImages”&images[][name]=“563f993e4b00ddad7ed42790_0.jpg”&images[][container]=“ offerImages”&images[][name]=“563f993e4b00ddad7ed42790_1.jpg"
And I would like it to be :
description="WhoGives"&images[0][container]=“offerImages”&images[0][name]=“563f993e4b00ddad7ed42790_0.jpg”&images[1][container]=“ offerImages”&images[1][name]=“563f993e4b00ddad7ed42790_1.jpg"
As anyone found how to do it? And if so, how?

You will need to use a .Custom parameter encoding to do this. Since there's no RFC spec published around collection URL encoding, Alamofire uses a common convention which works for many servers, but not all.
Here's a snippet from our ParameterEncoding docs.
Since there is no published specification for how to encode collection types, the convention of appending [] to the key for array values (foo[]=1&foo[]=2), and appending the key surrounded by square brackets for nested dictionary values (foo[bar]=baz).
To implement this, you'll want to leverage the logic in the encode method for the .URL case along with the queryComponents method. You'll need to make a slight change to the queryComponents method to put the array index in the parameter value. Then you should be good to go.

Related

Firebase REST API - POST Request

I'm trying to add records to my Firebase database as follows:
So basically we have matches -> user_supplied_id -> {id,location}
This is achievable using the following code and the Swift API:
let matches = Database.database().reference().child("users").child(UserDefaults.standard.object(forKey: "uid") as! String).child("matches").child((all_listings?[index].listingId)!)
let newBookData = [
"id": all_listings?[index].listingId,
"location" : all_listings?[index].location
] as [String : Any]
matches.setValue(newBookData)
I am now trying to replicate this behaviour using the Firebase REST API. I'm basically sending a POST request to the address:
https://PROJECTID.firebaseio.com/.../matches/-LOpJmU9yj4hAocHjnrB.json
with the following data:
"{\"id\":\"-LOpJmU9yj4hAocHjnrB\",\"location\":\"Edinburgh\"}"
However, this results in the following outcome instead:
As you can see, it creates an additional ID and level of nesting before adding the elements to the database. How can I fix this?
Don't use POST. According to the documentation:
To accomplish the equivalent of the JavaScript push() method (see Lists of Data), you can issue a POST request.
You don't want a push here. A push operation creates a new random push ID and makes that the key of the data you provided.
If already you know the location you want to set (it looks like you already have a known push id), just use a PUT to set the data at that location.

What is the best solution to pass two different parameters to a REST API?

I have a doubt about what could be the best way to define a REST URI for an API.
I have an API that provide the details of a commodity.
So I know that I can do a GET request like this:
http://XXX.YYY.ZZZ.TTT:8280/commodity_details/1
where commodity_details is what I want to obtain (a commodity details) and 1 is the ID of a specific commodity. This should be a proper REST URI.
Ok, I know that I can also pass the ID parameter into a JSON document doint a POST request like this:
http://XXX.YYY.ZZZ.TTT:8280/commodity_details/
and attacching a JSON payload like this to my POST request:
{
"commodity_id": 1
}
I think that if I have the single commodity_id parameter maybe is better the first version (putting the required ID into the URI), is it?
But what happens if I need a second language_id parameter? (my API should receive also this language_id parameters so it can provide an internazionalized output in the proper language.
So in this case I need to pass 2 parameters (commodity_id and language_id).
In this case is better use a POST request with a JSON payload that contains both the parameters? Something like this:
{
"commodity_id": 1,
"language_id": 2
}
Or what could be a good URI template for this scenario?
For passing just 2 parameters you can go with first approach(query string parameter) which is simpler to use
[HttpGet("{commodity_id}/{language_id}")]
public string GetCommodityDetails(string commodity_id, string language_id)
{
string commodityDetails=string.empty;
//your implementation
return commodityDetails;
}

How to POST / PUT edge with number property?

I am using Rexster to load data into a TitanDB. When posting / putting vertices, I can provide properties as JSON in the request's body. If a property's value is a number, it will correspondingly be stored as a number and can be retrieved as such. For example, the following body will in a post message will create a property "score" of type number:
{
"score": 5
}
When POSTing / PUTing edges, though, it seems properties can only be provided as query parameters, e.g.:
POST .../graphs/graph/edges?_outV=256&_label=review&_inV=512&score=5
In this case, unfortunately, the 5 is always considered as a string: "5". Consequently, queries including numeric operations / comparisons do not work. For example, the following query will still return the posted edge (despite the posted score being 5):
v(256).outE('review').filter{it.getProperty('score')>9}
Is there a way to POST / PUT edges and their properties so that the number type is considered?
I was reasonably sure you could POST JSON to the edge route, but even if you can't, you can use Rexster's explicit type system to post your integer properly:
$ curl -X POST "http://localhost:8182/graphs/tinkergraph/edges?_outV=1&_inV=2&_label=knows&score=(i,5)"
{
"version":"2.7.0-SNAPSHOT",
"results": {
"score":5,"_id":"0","_type":"edge","_outV":"1","_inV":"2","_label":"knows"
},
"queryTime":31.79554
}

ServiceStack Routing with ravendb ids

I've an entity with an ID of
public string ID {get;set;}
activities/1
(which comes from RavenDB).
I'm registering the following routes in my ServiceStack AppHost
Routes
.Add<Activity>("/activities")
.Add<Activity("/activities/{id}");
I'm using a backbone app to POST and PUT to my REST Service.
What happens out-of-the-box:
id property is serialized into the json as "activities/1"
id property is encoded into route as "activities%2F1"
ServiceStack gives precedence to the URL based id property, so my string gets the encoded value which is no use to RavenDb directly.
The options I'm aware of:
Change backbone to post to "/activities" and let the JSON Serialiser kick in
Change RavenDb ID generation to use hyphens rather than slashes
Make my Id property parse for the encoded %2F on set and convert to a slash
Both have disadvantages in that I either lose RESTfulness in my API, which is undesirable, or I don't follow RavenDb conventions, which are usually sensible out-of-the-fox. Also, I've a personal preference for having slashes.
So I'm wondering if there are any other options in servicestack that I could use to sort this issue that involve less compromise? Either Serialiser customisation or wildcard routing are in my head....
I have the same problem with ASP.Net WebAPI, so I don't think this is so much a ServiceStack issue, but just a general concern with dealing with Raven style id's on a REST URL.
For example, let's say I query GET: /api/users and return a result like:
[{
Id:"users/1",
Name:"John"
},
{
Id:"users/2",
Name:"Mary"
}]
Now I want to get a specific user. If I follow pure REST approach, the Id would be gathered from this document, and then I would pass it in the id part of the url. The problem here is that this ends up looking like GET: /api/users/users/1 which is not just confusing, but the slash gets in the way of how WebAPI (and ServiceStack) route url parameters to action methods.
The compromise I made was to treat the id as an integer from the URL's perspective only. So the client calls GET: /api/users/1, and I define my method as public User Get(int id).
The cool part is that Raven's session.Load(id) has overloads that take either the full string form, or the integer form, so you don't have to translate most of the time.
If you DO find yourself needing to translate the id, you can use this extension method:
public static string GetStringIdFor<T>(this IDocumentSession session, int id)
{
var c = session.Advanced.DocumentStore.Conventions;
return c.FindFullDocumentKeyFromNonStringIdentifier(id, typeof (T), false);
}
Calling it is simple as session.GetStringIdFor<User>(id). I usually only have to translate manually if I'm doing something with the id other than immediately loading a document.
I understand that by translating the ids like this, that I'm breaking some REST purist conventions, but I think this is reasonable given the circumstances. I'd be interested in any alternative approaches anyone comes up with.
I had this problem when trying out Durandal JS with RavenDB.
My workaround was to change the URL very slightly to get it to work. So in your example:
GET /api/users/users/1
Became
GET /api/users/?id=users/1
From jQuery, this becomes:
var vm = {};
vm.users = [];
$.get("/api/users/?" + $.param( { id: "users/1" })
.done(function(data) {
vm.users = data;
});

How we can handle dynamic web service in iPhone?

I am learning some tricky development in iPhone and during my experiments I found out that usually we used localized web-service in which all parameter are fixed(Keyword). If my web service will change some fields in the response than how can we handle in iPhone. Please help me. If Anybody have any good idea.
For Example,
Webservice Response1:
[    {
      "Number":"A12 hrb",
      "List":[
         {
            "Type":"Works",
            "Display":{
               "dop":45,
               "dopper":56
            },
            "OAST":"10-01-2012",
            "OAET":"07-04-2012",
            "Cause":"define",
            "Impact":"Queue",
            "Description":"Take a Break.",
            "LName":"Lunetten To Lunetten",
            "Number":"A12 hrb",
         }
      ]    },   ]
Webservice Response2:
[    {
      "Number":"A12 hrb",
"Number2":"A13 brs",
      "List":[
         {
            "Type":"Works",
            "Display":{
               "dop":45,
               "dopper":56
"picker":90
            },
            "OAST":"10-01-2012",
"MAET":"07-04-2012",
            "OAET":"07-04-2012",
            "Cause":"define",
            "Impact":"Queue",
            "Description":"Take a Break.",
            "LName":"Lunetten To Lunetten",
            "Number":"A12 hrb",
         }
      ]    },   ]
You can do this
Parse the response.If response is JSON then definitely you will get a dictionary just keep a reference of it.
you can get all the keys in dictionary by calling following method
(NSArray *)allKeys
now enumerate above array and access the values respective to each key and do whatever you want
But you should know the meaning/purpose of dynamic keys. If you don't no meaning/purpose of keys these steps may not help you... best of luck.
For this type of case you can get the dictionary and in dictionary you
can get the value of which tag you want means you just need root node
and store root node all the data in dictionary and handle that
dictionary for the further use..
I don't think it will be possible to parse it completely. Atleast you should know which keys are going to be there. e.g. response has Number, Number2 & List as keys. It's ok if some responses do not contain one/some of the keys.
On the other hand, if knowing all the keys in advance is at all not possible, then webservice should have mechanism to convey the keys used in response.
e.g. [ {
"dynamic_keys": "Number2",
"Number":"A12 hrb",
"Number2":"A13 brs",
"List":[
{
"Type":"Works",
"Display":{
"dop":45,
"dopper":56
"picker":90
},
"OAST":"10-01-2012",
"MAET":"07-04-2012",
"OAET":"07-04-2012",
"Cause":"define",
"Impact":"Queue",
"Description":"Take a Break.",
"LName":"Lunetten To Lunetten",
"Number":"A12 hrb",
}
] }, ]
You can read the value of "dynamic_keys" and then using that value you can read value of actual dynamic key.
edit: as mentioned by ssteinberg you can use some framework like JSONKit to parse actual JSON.
See this as well: How to parse JSON having dynamic key node