RestKit resolve objects given an id or partial representation in JSON - objective-c

I have a JSON array, something like:
[{
"name": "John Smith",
"occupationId": 3
},
{
"name": "Steven Davis",
"occupationId": 2
}
]
The occupation response looks something like:
[{
"id": 2,
"name": "Teacher"
},
{
"id": 3,
"name": "Teaching Assistant"
}
]
Is there a way to allow RestKit to request the correct data for the occupations, given only their id? I know this can be done if the data is persisted using CoreData, via the addConnectionForRelationship:connectedBy: method, but I would rather that the data is transient, given that the server is local and there really is no need to persist the data. I'm also aware that RKObjectMapping does not support the identifiactionAttributes property, meaning I cannot (to my knowledge) designate a way to allow the class to declare a unique, identifying property.
Any help would be appreciated. I am using a mix of Objective-C and Swift, and as such, I do not mind answers in either language.

Related

JSON Schema - field named "type"

I have an existing JSON data feed between multiple systems which I do not control and cannot change. I have been tasked with writing a schema for this feed. The existing JSON looks in part like this:
"ids": [
{ "type": "payroll", "value": "011808237" },
{ "type": "geid", "value": "31826" }
]
When I try to define a JSON schema for this, I wind up with a scrap of schema that looks like this:
"properties": {
"type": { <====================== PROBLEM!!!!
"type": "string",
"enum": [ "payroll", "geid" ]
},
"value": {
"type": [ "string", "null" ],
"pattern": "^[0-9]*$"
}
}
As you might guess, when the JSON validator hits that "type" on the line marked "PROBLEM!!!" it gets upset and throws an error about how type needs to be a string or array.
That's a bug in the particular implementation you're using, and should be reported as such. It should be able to handle properties-that-look-like-keywords just fine. In fact, the metaschema (the schema to valid schemas) uses "type" in exactly this way, along with all the other keywords too: e.g. http://json-schema.org/draft-07/schema
I wonder if it is not making use of the official test suite (https://github.com/json-schema-org/JSON-Schema-Test-Suite)?
You didn't indicate what implementation you're using, or what language, but perhaps you can find an alternative one here: https://json-schema.org/implementations.html#validators
I found at least a work-around if not a proper solution. Instead of "type" inside "properties", use "^type$" inside "patternProperties". I.e.
"patternProperties": {
"^type$": {
"type": "string"
}
}
Unfortunately there doesn't seem to be a great way to make "^type$" a required property. I've settled for listing all the other properties as "required" and setting the min and max property counts to the number that should be there.

Design pattern - update join table through REST API

I'm struggling with a REST API design concept. I have these classes:
user:
- first_name
- last_name
metadata_fields:
- field_name
user_metadata:
- user_id
- field_id
- value
- unique index on [user_id, field_id]
Ok, so users have many metadata and the type of metadata is defined in metadata_fields. Typical HABTM with extra data in the join table.
If I were to update user_metadata through a Rails form, the data would look like this:
user_metadata: {
id: 1,
user_id: 2,
field_id: 3,
value: 'foo'
}
If I posted to the user#update controller, the data would look like this:
user: {
user_metadata: {
id: 1,
field_id: 3,
value: 'foo'
}
}
The trouble with this approach is that we're ignoring the uniqueness of the user_id/field_id relationship. If I change the field_id in either update, I'm not just changing data, I'm changing the meaning of that data. This tends to work fine in Rails because it's somewhat of a walled garden, but it breaks down when you open up an API endpoint.
If I allow this:
PATCH /api/user_metadata
Then I'm opening myself up to someone modifying the user_id or field_id or both. Similarly with this:
PATCH /api/user/:user_id/metadata
Now user_id is set but field_id can still change. So really the only way to solve this is to limit the update to a single field:
PATCH /api/user/:user_id/metadata/:field_id
Or a bulk update:
PATCH /api/user/:user_id/metadata
But with that call, we have to modify the data structure so that the uniqueness of the user_id/field_id relationship is intact:
user_metadata: {
field_id1: 'value1',
field_id2: 'value2',
...
}
I'd love to hear thoughts here. I've scoured Google and found absolutely nothing. Any recommendations?
As metadata belongs to a certain user /api/user/{userId}/metadata/{metadataId} is probably the clean URI for a single metadata resource of a user. The URI of your resource is already the unique-key you are looking for. There can't be 2 resources with the same URI! Furthermore, the URI already contains the user and field IDs.
A request like GET /api/user/1 HTTP/1.1 could return a HAL-like representation like the one below:
{
"user" : {
"id": "1",
"firstName": "Max",
"lastName": "Sample",
...
"_links": {
"self" : {
"href": "/api/user/1"
}
},
"_embedded": {
"metadata" : {
"fields" : [{
"id": "1",
"type": "string",
"value": "foo",
"_links": {
"self": {
"href": "/api/user/1/metadata/1"
}
}
}, {
"id": "2",
"type": "string",
"value": "bar",
"_links": {
"self": {
"href": "/api/user/1/metadata/2"
}
}
}],
"_links": {
"self": {
"href": "/api/user/1/metadata"
}
}
}
}
}
}
Of course you could send a PUT or a PATCH request to modify an existing metadata field. Though, the URI of the resource will still be the same (unless you move or delete a resource within a PATCH request).
You also have the possibility to ignore certain fields on incomming PUT requests which prevents modification of certain fields like id or _link. I'll assume this should also be valid for PATCH requests, though will have to re-read the spec again therefore.
Therefore, I'd suggest to ignore any id or _link fields contained in requests and update the remaining fields. But you also have the option to return a 403 Forbidden or 409 Conflict response if someone tries to update an ID-field.
UPDATE
If you want to update multiple fields within a single request, you have two options:
Using PUT and replace the current set of fields with the new version
Using PATCH and send the server the necessary steps to transform the current field-set to the new field-set
Example PUT:
PUT /api/user/1/metadata HTTP/1.1
{
"metadata": {
"fields": [{
"type": "string",
"value": "newFoo"
}, {
"type": "string",
"value": "newBar"
}]
}
}
This request would first delete every stored metadata field of the user the metadata belong to and afterwards create a new resoure for each contained field in the request. While this still guarantees unique URIs, there are a couple of drawbacks to this approach however:
all the data which should be available after the update, even fields that do not change, need to be transmitted
clients which have a URI pointing to a certain resource may point to a false representation. F.e. a client has retrieved /user/1/metadata/2right before a further client updated all the metadata, the IDs are dispatched via auto-increment, the update however introduced a new second item and therefore moved the former 2 to position 3, client1 has now a reference to /user/1/metadata/2 while the actual data is /user/1/metadata/3 however. To prevent this, unique UUIDs could be used instead of autoincrement IDs. If client 1 later on tries to retrieve or update former resource 2, his can be notified that the resource is not available anymore, even a redirect to the new location could be created.
Example PATCH:
A PATCH request contains the necessary steps to transform the state of a resource to the new state. The request itself can affect multiple resources at the same time and even create or delete other resources as needed.
The following example is in json-patch+json format:
PATCH /api/user/1/metadata HTTP/1.1
[
{
"op": "add",
"path": "/0/value",
"value": "newFoo"
},
{
"op": "add",
"path": "/2",
"value": { "type": "string", "value": "totally new entry" }
},
{
"op": "remove",
"path": "/1"
},
]
The path is defined as a JSON Pointer for the invoked resource.
The add operation of the JSON-Patch type is defined as:
If the target location specifies an array index, a new value is inserted into the array at the specified index.
If the target location specifies an object member that does not already exist, a new member is added to the object.
If the target location specifies an object member that does exist, that member's value is replaced.
For the removal case however, the spec states:
If removing an element from an array, any elements above the specified index are shifted one position to the left.
Therefore the newly added entry would end up in position 2 in the array. If not an auto-increment value is used for the ID, this should not be a big problem though.
Besindes add, and remove the spec also contains definitions for replace, move, copy and test.
The PATCH should be transactional - either all operations succeed or none. The spec states:
If a normative requirement is violated by a JSON Patch document, or if an operation is not successful, evaluation of the JSON Patch document SHOULD terminate and application of the entire patch document SHALL NOT be deemed successful.
I'll interpret this lines as, if it tries to update a field which it is not supposed to update, you should return an error for the whole PATCH request and therefore do not alter any resources.
Drawback to the PATCH approach is clearly the transactional requirement as well as the JSON Pointer notation, which might not be that popular (at least I haven't used it often and had to look it up again). Same as with PUT, PATCH allows to add new resources inbetween existing resources and shifting further ones to the right which may lead to an issue if you rely on autoincrement values.
Therefore, I strongly recommend to use randomly generated UUIDs as identifier rather than auto-increment values.

RestKit: Composing Relationships with the Nil Key Path

I have two classes
Author with attributes id, papers (Paper relationship), ...
Paper with attributes id, mainAuthor (Author relationship), authors (Author relationship) ...
and want to map some JSON to it
"authors": [
{
"id": 123,
"papers": [
{
"id": 1,
"main_author_id": 123,
...
},
...
]
},
...
]
The problem is that the JSON is not structured like
"authors": [
{
"id": 123,
"papers": [
{
"id": 1,
"main_author": {
"id": 123
}
...
},
...
]
},
...
]
so that I could easily map things (note the *main_author* part of both JSON examples). I tried using mapping this value without a key path as explained here:
[authorMapping addAttributeMappingToKeyOfRepresentationFromAttribute:#"main_author_id"];
[authorMapping addAttributeMappingsFromDictionary:#{#"(main_author_id)": #"id"}];
but I'm getting an error telling me that the keyPath id already exists and I may not add a second mapping for this keyPath. I totally understand this error, but I have no idea how to map from *main_author_id* back to id. Changing the data source may be the best solution, but this is unfortunately not possible.
Any suggestion is highly welcome! Thanks!
This is exactly what foreign key mapping is for. It allows you to temporarily store the 'identity' value that you're provided with and then RestKit will find the appropriate object and complete the relationship.
Apart from the Answer #Wain (foreign key mapping) provided, it is also possible to implement a custom serialization (c.f. RKSerialization) and modify the objects before mapping takes place. However, the aforementioned method is superior to this (somehow ugly) solution.

RestKit: Map single object into existing array

I have the following JSON structure which i get from a RestService:
{
"customer": {
"id": "123456",
[more attributes ....]
"items": [
{
"id": "1234",
},
{
"id": "2345",
}
[more items...]
]
}
}
which i successfully map into Core Data using RestKit. From another RestService (which i can not change) i then get more details to one single item in the items array. the JSON answer looks like
{
"customer": {
"id: "123456",
"item": {
"id": "1234",
"name": "foo",
[other attributes...]
}
}
}
Now the question: How can i map the second answer, so that the single item is added to the items array (or updated if it is already in there)?
Thanks for any ideas!
If you already know how to map JSON to Core Data, all that's left is just fetch theobject you want to add your item attributes to(using id or something else) and then just set it,rewriting the old one,or adding new fields.That's just general approach
If you set the appropriate primaryKeyAttribute of the RKManagedObjectMapping object you should be able to perform the mapping as you want it to.
It would actually be easier to help you, if you would post some of your mapping code, but this is how I meant it to be
Create the mapping for your customer object, defining all possible attributes and declare the mappingObject.primaryKeyAttribute = #"id"
Execute the mapping with the first request (or first answer as you put it)
After the first mapping step is finished execute the second request
This should initially create the customer objects you want and then update them.

Is RestKit the only framework that has JSON to Objective-C objects mapping?

I am looking for a library or framework that does JSON to Objective-C relational object mapping.
i.e. I need to map JSON containing objects, array of objects and dictionaries of objects to my custom objects.
something like:
DataObject {
"user" : {
"name":"Peter",
"id":1234
}
"place": "UK"
"job": {
"title" : "CTO",
"salary" : 1234567
}
"employess": [
{
"name":"Carlton",
"id":1235
},
{
"name":"Hugo",
"id":12346
}]
}
So there is a DataObject a UserObject and an employees array consisting of UserObjects.
I would like for the mapping from the JSON to my DataObject to happen "automatically", of course meant as I would like to describe the objects and there relations in the Object class and have the mapping done from this, instead of manually mapping each nested object.
(First level native objective-c properties are easily done with setValue:forKey and other KVO methods, but from there on it gets complicated).
I have been testing out RestKit but it seems there is no way to pick and choose which functionality you need from that framework, it is either all of it or none of it, and I do find it does too much for my needs.
Are anyone familiar with a library etc. out there that can do this?
Thank you in advance.
To map JSON to Objective-C objects, I have tried RestKit. I used it a while ago, so my criticisms might not apply anymore.
What I found out: nice idea. Not too complicated to plug-in. If it works, great for you. But if not, or if you need to push it a bit further, good luck to debug.
I regret the time I invested in it.
I am only looking for JSON to Objective-C objects, not the other way around.
I found a link on SO to JTObjectMapping - but can't find the original answer. Seems more lightweight and close to what I was searching, but I did not had the opportunity to try it.
An other similar class: jastor.
I prefer the approach of this two classes over RestKit, as it only takes care of one job, whereas RestKit tried to handle everything.
What you have posted above isn't valid JSON. If you made it valid JSON what you want to do is impossible without a specific schema, eg.
{
"DataObject": {
"user": {
"name": "Peter",
"id": 1234
},
"place": "UK",
"job": {
"title": "CTO",
"salary": 1234567
}
}
}
Is Dataobject a dictionary or an Object? What about User or Job? What is User is an instance of NSUser and job is an NSDictionary?
On the other hand, if you have a known schema:-
[
{
"class": "DataObject",
"properties": {
"user": {
"class": "User",
"properties": {
"name": "Peter",
"id": 1234
}
},
"place": "UK",
"job": {
"title": "CTO",
"salary": 1234567
}
}
}
]
you don't need a framework as it is trivial to map to your objects yourself once you have valid JSON. Pseudocode:-
createWithDict(dict) {
var newOb = create new(dict["class"]);
dict.properties.each( val, key ) {
if(val is dictionary && val.hasproperty("class"))
val = createWithDict(val)
newOb[key] = val
}
return newOb;
}