Should I sent images through JSON - json

I'm new to Django, and I'm building a REST backend for my iOS app, I figured out encode an Image to it's Base64 data, and I would like to use it together with some texts, is it a good idea to put it into the JSON for the rest of the data or is it better to use another request to download each image data.
I'm guessing that separating concerns is the best way, and have two GET request to retrieve the data, but I just want to be sure!.
OPTION A
{
"owner": {
"username": "lilysmith",
"email": "lily#email.com",
"first_name": "Lily",
"last_name": "Smith"
},
"is_user_page": true,
"title": "Lily Smith",
"subtitle": "Photographer",
"about": [
{
"icon": "🇺🇸",
"label": "Austin, TX"
}
],
"photos": [
{
"position": 2,
"description": "I love hiking",
"photo": "/9j/2wCEAAgGBg....CEAAgGBg" <- (The rest of the binary data)
}
]
}
OPTION B (Separating Concern)
The same JSON response, but instead of image data, using it's id.
Then getting it just the data through another request, but esencially making the front end handle two or more request to server.

Related

How to send structured data to a REST endpoint that retrieves objects? Which HTTP verb should be used?

I want to construct a REST endpoint to retrieve objects, but I need to send structured data as query parameters (e.g. a list). I was wondering if those data could be sent as request body (see example below). How should I handle this in order to stick to REST good practices? Which HTTP verb should I use?
URI:
http://localhost:8080/products
Request Body:
{
"name" : "Computer",
"categories" : [
{
"id" : 1
},
{
"id" : 4
}
]
}
Response:
[
{
"id": 2,
"name": "Computer XP 2040",
"price": 800
},
{
"id": 1,
"name": "HP Computer",
"price": 2000
},
{
"id": 7,
"name": "Smart Computer",
"price": 1200
}
]
POST is not correct for this. If you want to stick to RESTful best practices, you must encode the information in the uri.
Note that POST might be better if you don't want to do this, but since this question was about REST best practices (and not http services in general), POST is your go-to.
I would simply encode this as:
GET /products?name=Computer&categories=1,4

REST API response describing request and returned data

Before implementation I'm considering the structure of JSON response that produces REST API I'm working on. I went through many Q/A here on SO, read many articles, recommendations and pseudo standards.
Requirements
Inform client about some useful meta information - HTTP status code etc.
Paging and filtering information - offset, limit and filtering queries (API client is aware of all parameters that influenced the result).
Information about data collection - total records count in collection and number of returned items. API client is then able create pagination.
Links to previous and next pages (just considering, not sure if this is useable for API clients but many REST APIs links section use - e.g. PayPal)
Response
This is my first draft of structure of returning search results data:
{
"meta": {
"status_code": 200,
"success": true,
"server_time": "2017-06-29T15:24:40+0200"
},
"request": {
"offset": 5,
"limit": 5,
"query": [
"foo",
"bar"
]
},
"response": {
"count": 5,
"total_count": 754,
"data": [
{
"id": "88b60cc6-70bc-4b1a-8f26-c919355d47d3",
"name": "Name of entity 1"
},
{
"id": "2f4ccda5-11bc-4ef7-b663-30c506f5118c",
"name": "Name of entity 2"
},
{
"id": "1333f2fe-a958-474e-9a82-8b343fda3aff",
"name": "Name of entity 3"
},
{
"id": "f5187143-f3b8-412b-a416-1e3a5830baee",
"name": "Name of entity 4"
},
{
"id": "2dd17750-bbdf-460a-abec-1f74e1170726",
"name": "Name of entity 5"
}
]
},
"links": {
"previous": {
"href": "http:\/\/api.example.com\/envelopes?offset=0&limit=5",
"rel": "previous",
"method": "GET"
},
"self": {
"href": "http:\/\/api.example.com\/envelopes?offset=5&limit=5",
"rel": "self",
"method": "GET"
},
"next": {
"href": "http:\/\/api.example.com\/envelopes?offset=10&limit=5",
"rel": "next",
"method": "GET"
}
}
}
I would like to avoid an "opinion question" to discuss the most appropriate JSON structure. I saw many opinions about envelopes in response, some services / standards it recommends, some not.
Questions:
Is it good idea to return the result in this structure?
Do you see some problems with this structure? What to do better?
Do you see some missing values that are needed for API client? Some unnecessary values?
Is needed return URL to self?
Opinion questions are hard, but I'll try.
First of all, your question should not be addressed to community, but to client itself. Nothing clears assumptions about missing/necessary values better than such feedback.
The structure itself is good enough, at least as a draft. When designing responses you need to remember that you are basically locking yourself up, since clients don't like fundamental changes in API. Only lot of incremental "please add just one more field here". You are doing good job in thinking far enough, about meta fields, pagination and separating actual response, but don't think you can predict everything. You won't. Maybe look for something like HAL or JSON Collection. At least as an inspiration.
In the end design of API is evolutionary and mostly client driven process. So talk to your client.

Graph API: Check if feed post was made by a Page or User

When using the /page/feed endpoint in the Facebook Graph API I can't figure out how to know if the post was made by a Page or a User
Here's how I call the endpoint right now:
HTTP GET https://graph.facebook.com/v2.8/{page_id}/feed?fields=is_published,from,message
This yields the following JSON response:
{
"data": [
{
"from": {
"name": "Chad Smith", # <-- This is a User
"id": "806273209398023"
},
"message": "A really magical place! Best Christmas...",
"id": "103988597020_1445496708809010"
},
{
"from": {
"name": "Tivoli", # <-- This is a Page
"id": "103988597020"
},
"message": "Hello everybody...",
"id": "103988597020_10154040865527021"
},
]
}
How can I know if the post was from a Page or User without making additional API calls? I've tried using subfields, but can't figure out if they work on the from field.
I solved it by using ?fields=from{name,about} and marking it as a Page if the from JSON contains about.
This is not the best solution, but about is currently the only subfield of from that doesn't fail on User. (e.g. if I was using ?fields=from{fan_count} the Graph API will fail for posts made by User objects.

Reading complex json data without iteration

I am working with some data and often the data is nested and i am required to perform some CRUD operations based on the structure of the data i have. For instance i have this json structure
{
"_id": "KnNLkJEhrDsvWedLu",
"createdAt": {
"$date": "2016-10-13T11:24:13.843Z"
},
"services": {
"password": {
"bcrypt": "$2a$30$1/cniPwPNCuwZ/MQDPQkLej..cAATkoGX.qD1TS4iHgf/pwZYE.j."
},
"email": {
"verificationTokens": [
{
"token": "qxe_T9IS7jW7gntpK0Q7UQ35RJ9jO9m2lclnokO3z87",
"address": "drwho#gmail.com",
"when": {
"$date": "2016-10-13T11:24:14.428Z"
}
}
]
},
"resume": {
"loginTokens": []
}
},
"username": "doctorwho",
"emails": [
{
"address": "drwho#gmail.com",
"verified": false
}
],
"persodata": {
"lastlogin": {
"$date": "2016-10-13T11:29:36.816Z"
},
"fname": "Doctor",
"lname": "Who",
"mobile": "+4480000000",
"identity": "1",
"email": "drwho#gmail.com",
"gender": null
}
}
I have several data sets with such complex structure. I need to read the data, edit and also delete. Before i get to iteration, i was wondering how i can read the data without iteration then iterate when i absolutely have to.
What are the rules i should keep in mind when reading such complex json structures to enable me read any complex structure i come across?.
I am currently using javascript but i am looking for rules that apply in other languages as well.
Parsing Json in JavaScript should be easy. http://www.json.org/js.html.
"Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure". Just follow the examples on that page.
If you want to use another language, in Java you could use Jackson or Gson to map those json strings to objects. Then using them becomes easy. Both libraries are annotation based, and wouldn't be difficult to implement.

How to merge JPA entity structure on a POST/PUT RESTful webapp

I am starting to implement a REST layer to an existing JSF-webapp (using RESTEasy, with a Jettison provider). Since tutorials for Java REST layers are quite basic (simple objects) I am facing the question how existing JPA entity relations can be easily exposed to/consumed from the client. A simple "/user" REST-method already gives me successfully the output below, which is a good start. But my main question is - how to deal with this kind of structures. Is it common to use such structures through REST?
I don't want to expose all details or the whole entity-tree, wether it is because of irrelevance, saving traffic or security issues. Using #XmlTransient works fine for the #Procudes, but merging these entities on a #POST/#PUT all #XmlTransient properties are merged to NULL. What is right way of doing that?
Since #XMLTransient is a global and permanent setting - what is the right approach to dynamically decide which depth of entity-tree I want to expose?
thanks
Example JSON of User-entity:
{
"user": {
"id": ..,
"uuid": "1521ccad69ba4579bbe49e75181fefc1",
"image": "",
"contact": {
"id": ..,
"uuid": "8eb429dcca994834ae5c8cf07cba62a2",
"cellphone": "",
"city": "",
"country": "",
"email": "mail#foo.bar",
"fax": "",
"phone": 555,
...
},
"name": "...",
"account": {
"id": ...,
"uuid": "80b331f9e6644449bb3600b0e5145253",
"confirmed": true,
"profile": {
"id": ...,
"uuid": "e172bdcafe2645d7975852ca5685c98c",
"locale": "en",
"notifyMessage": false,
"notifyNews": true,
"notifyTask": true,
"timeZone": "Europe/Berlin"
},
"roleProfiles": {
"id": ..,
"uuid": "f1713758f3f2416faed3e68350f2d759",
"active": true,
"assemblies": [
{
"id": ..,
"uuid": "13d72449833a4eb0b5b4f62c729ee44f",
"image": "",
"commercialRegisters": [
123,
456
],
"contact": {
"id": ...,
"uuid": "bef3802297344e3c8c3619b6c91c345a",
"city": "",
"country": "",
...
},
"thumbnail": ""
},
{
...
}
],
},
"userName": "..."
},
"displayName": "...",
"firstName": "Foo",
"lastName": "Bar",
"salutation": "",
"title": ""
}
}
Hi references in your Java classes should be serialized to JSON as links and not as values.
This is how Spring REST does it.
The good thing is : That way you have a kind of lazy loading
The bad thing is that the client needs additional requests to get the values of the references.
I developed a complete solution for that, but that was a hard piece of work.
The client (in javascript) creates proxies for those references and resolves them on demand.
I have a demo of that at demo.appdriver.com
In the upper right corner you see a link 'REST API' click it and you can see the REST API of a rather complex domain model.
Now you can start to click on the user interface , create, change, delete etc.
and have a look at the traffic between client and server.
Hope it helps !