Swift: Alamofire + Nutritionix API - json

I'm trying to use Alamofire 3.3 with the Nutritionix API.
I was able to get a few requests going however i'm having issues to get usda_fields.
var params = [
"appId" : MY_APP_ID,
"appKey" : MY_APP_KEY,
"fields" : ["item_name", "brand_name", "keywords", "usda_fields"],
"limit" : "50",
"query" : searchString,
"filters" : ["exists":["usda_fields": true]]
]
Alamofire.request(.GET, "https://api.nutritionix.com/v1_1/search/", parameters: params)
.responseData { response in
print(response.request)
print(response.response)
print(response.result)
}
For some reason I realized that 'fields' shouldn't be in an array and just follow each others separated by a coma. Then the query return something however the filter doesn't seem to work.
Any help appreciated thanks!

If you are still looking to solve this, I recommend trying the 2.0 version of our API instead of the 1.1 version. Here are the details:
https://developer.nutritionix.com/docs/v2
Feel free to email us at api at nutritionix dot com if you have more questions about the API!

Related

Postman: POST request of nested JSON via form-data not working (while via raw-data ok)

I want to POST the following JSON-object via Postman:
{
"title": "test_title",
"date": "2021-12-31",
"attachments": [
{
"name": "test_attachment"
}
]
}
This works perfectly fine, when using Postman's raw input form for the request-body: I get a "201 Created"-response back.
However, when using the form-data to POST the data, I get the error "Invalid data. Expected a dictionary, but got str." (see also screenshot below) What am I doing wrong here? I tried all kind of other versions to enter the attachment-key:value pair but nothing worked so far
I managed to make it work! (note: I added some additional fields compared to the screenshot in question. See below for details:
You did nothing wrong.
If you want to make a request with json object, then you go with raw type (json) in postman.
If you want to upload file, then you use form-data
One more thing, status 201 means the request is succeed, your object has been created.
var express = require('express')
const multer = require('multer')
const upload = multer()
var app = express()
app.use(express.json());
app.post('/test',upload.none(), function (req, res, next) {
res.send(req.body)
})
app.listen(80, function () {
console.log('web server listening on port 80')
})
Above is a sample endpoint which works with both form-data and json , just do a post to http://localhost:80/test with both form data and raw json
you can see both will get parsed correclty
APIs are just abstraction , its like a function that takes in many attribute, how you parse it depends on the implementation ( how the api function is written) .
so answer is "Talk to the developer" on how the API is implemented and what it is supporting
I'm having issue in placing json into form format the way Daniel did in Postman. Need help in figuring out what is it required to place the cascaded json objects into form data format. Please see here that I'm trying to accomplish.
JSON Format (to be filled into Postman form-data section:
{
"primary_object": {
"child_object_1": [{"id": 12345678, "value": "abc"},{"id": 87654321, "value": "xyz"}],
"child_object_2": [
"first_val",
"second_val"
]
}
}

How can I get common response format for Lambda API?

I am using Node.js for AWS Lambda + API Gateway APIs.
I have multiple Lambda functions and each giving different response formats as it integrated multiple third party SDKs like Stripe/DynamoDB and all.
Is there any way to get common response for all the functions like below?
{
"success" : true,
"data" : { RESPONSEFROMLAMBDA },
"messages" : null,
"code" : 200,
"description" : "OK"
}
The third-party services your Lambda functions are using shouldn't have any bearing on the response format. You just need to update all the API Gateway endpoints to use a mapping template with this format.

Best way to do authorisation through REST API using Lumen?

I am making a simple REST API using latest stable version of Lumen. That API is going to be used in mobile applications, and there is one thing I'm not sure about.
What is the best ( secure enough ) way to an authorization? At the moment I am doing a simple POST request to the server url like http://api.example.com/v1/auth with username and password parameters and return a JSON response like
{ "code" : 200, "message" : "OK", "access_token" : string }
or
{ "code" : 401, "message" : "Unauthorized" }
Is JSON response a good solution?
Is it better to return response code within header?
Have you checked this? https://softwareengineering.stackexchange.com/questions/183665/the-best-way-to-implement-authorization-for-a-rest-api
200 and 401 seem the "standard" response to me.

How track json request sent to Elasticsearch via elastic4s client?

Say that I use such code:
ElasticClient client = ...
client.execute{search in "places"->"cities" query "paris" start 5 limit 10}
How to see what json request was been sent to Elasticsearch?
In Elastic4s 1.6.2 you can use the show typeclass on a number of requests to get the JSON equivilent.
It's pretty straightforward.
val req = search in "index" / "type" query "kate bush"
logger.debug(s"Search request ${req.show}")
The .show method will render JSON output. It works on most of the request types.
In Elastic4s 5.2.0+, you use the show method on the client.
val req = search("index" / "type").query("kate bush")
client.show(req)
I did not find build-in feature to track every request via elastic4s client, but there is a _builder variable in elastic4s which you can use to print request before execute it:
println(search in "places"->"cities" query "paris" start 5 limit 10 _builder) toString
{
"from" : 5,
"size" : 10,
"query" : {
"query_string" : {
"query" : "paris"
}
}
}

Pivotal Tracker API Labels

I am trying to use the Pivotal Tracker API to post a story using python. I am able to do so using the python requests module. The following is a sample code that I can use to create a new story:
payload = {"name":"Create story w/create label"}
requests.post('https://www.pivotaltracker.com/services/v5/projects/xxxxxx/stories', data=payload4, headers={'X-TrackerToken':token}).json()
for which the output is
{u'created_at': u'2015-03-04T18:47:28Z',
u'current_state': u'unscheduled',
u'id': xxxxxx,
u'kind': u'story',
u'labels': [],
u'name': u'Create story w/create label',
u'owner_ids': [],
u'project_id': xxxxxx,
u'requested_by_id': xxxxxx,
u'story_type': u'feature',
u'updated_at': u'2015-03-04T18:47:28Z',
u'url': u'https://www.pivotaltracker.com/story/show/xxxxxx'}
Great. Now, I want to create a story and add a label to it. According to the POST /projects/{project_id}/stories API on https://www.pivotaltracker.com/help/api/rest/v5, I should be able to format my json as follows and run a POST request:
payload = {"name":"Create story w/create label","labels":[{"name":"orbit"}]}
requests.post('https://www.pivotaltracker.com/services/v5/projects/xxxxxx/stories', data=payload, headers={'X-TrackerToken':token}).json()
however, I get the following 400 response:
{u'code': u'invalid_parameter',
u'error': u'One or more request parameters was missing or invalid.',
u'general_problem': u"'labels' must be an array of label values",
u'kind': u'error'}
From what I understand, the way I formatted the payload json is correct and the label resource json is formatted properly. I'm not sure if the error is on my end or if it is something else. If someone with knowledge of the API could provide some help, it would be much appreciated.
Thanks
Solved it, there' s a JSON encoding issue. We never told pivotal tracker that we were sending JSON. This code snippet works:
data = {
"labels": ["major request"],
"name": "some cool feature",
"description": "solve world hunger",
"comments": ["requested by not the 1%"]
}
headers = {'X-TrackerToken': TRACKER_TOKEN,
'Content-type': 'application/json',
'Accept': 'application/json'
}
return requests.post(url, headers=headers, data=json.dumps(data))
Need to tell the API that we are sending JSON and accepting JSON.