In spray how to unmarshall plain/text? - scala

Can anybody show me an example in spray how to unmarshall POST with content type plain/text ?
How to write the route?
Thanks!

This is how the route would look like:
post {
entity(as[String]) { str =>
complete(str)
}
}
A sample request would be:
curl -X POST -d 'It works' localhost:8080
which echoes back the POST data.
To get the whole sample app use this official template and add/edit the route.
If you want to understand how it works in detail see this doc and this one.

Related

Get ads and their image in the same query

I'm using the graph API and trying to get a list of ads with their insights and post images.
I don't want to do multiple queries for this as I quickly hit the "(#17) User request limit reached" issue even when I use batch queries.
My current query looks like this:
/ACCOUNT_ID_HERE/ads?fields=insights{cpc,reach,spend,clicks,ctr},status,creative
Now in order to get the post image, I need to take the creative ID that is returned and use it in another query to pull the post like this:
/CREATIVE_ID/?fields=object_story_id
Then use the returned story id to pull the picture like:
/OBJECT_STORY_ID/?fields=picture
Is there any way I can combine these queries to do less requests?
Something like:
/ACCOUNT_ID_HERE/ads?fields=insights{cpc,reach,spend,clicks,ctr},status,creative{object_story_id{picture}}'
Any help is appreciated. Thanks.
Facebook's Batch API may work for you. It allows for multiple Graph API calls to be made from a single HTTP request and supports dependencies between those requests. Read over the documentation for details and here's a example curl call of how it might work (I've not executed this call so please review against the API documentation and test).
curl \
-F 'access_token=...' \
-F 'batch=[
{
"method":"GET",
"name":"ads",
"relative_url":"/ACCOUNT_ID_HERE/ads?fields=insights{cpc,reach,spend,clicks,ctr},status,creative",
},
{
"method":"GET",
"name":"creative",
"relative_url":"/{result=ads:$.data.*.creative}/?fields=object_story_id"
},
{
"method":"GET",
"relative_url":"/{result=creative:$.data.*.object_story_id}/?fields=picture"
}
]' \
https://graph.facebook.com

How to make a correct HTTP Post request with Meteor.js to Domino Datalab's Rest API

In my server side Meteor.js method, I'm trying to correctly make a request to Domino Data Lab's (DDL) Rest API.
DDL provides a platform for makes it possible to call a data science model via a REST API. Their documentation on this API is here:
http://support.dominodatalab.com/hc/en-us/articles/204173149-API-Endpoints-Model-Deployment
But, I doubt the documentation is helpful because I think an experienced Meteor developer will see the request examples in CURL or Python and know how to get the params correctly into the JSON format that DDL is looking for.
Domino Datalab provides the instructions for 4 methods, but not for Meteor.js. I'll post the examples for Curl and Python:
Examples
CURL Request
curl -v -X POST \
https://app.dominodatalab.com/MYURL \
-H 'Content-Type: application/json' \
-H 'X-Domino-Api-Key: YOUR_API_KEY' \
-d '{"parameters": [ "FOO", "BAR", "ETC"]}'
Python Request
import requests
response =
requests.post("https://app.dominodatalab.com/MYURL",
headers = {
"X-Domino-Api-Key": "YOUR_API_KEY",
"Content-Type": "application/json"
},
json = {
"parameters": ["FOO", "BAR", "ETC"]
}
)
print(response.status_code)
print(response.headers)
print(response.json())
I've tried a few different ways (using both the dataand paramsoptions) based on the documentation for Meteor, but here is my best try:
Meteor.methods({
score_app: function(){
var test = HTTP.call("POST", "https://app.dominodatalab.com/MYURL",
{ headers: {
"Content-Type": "application/json",
"X-Domino-Api-Key": "YOUR_API_KEY"
},
// This is where the problem is. Have tried multiple syntax versions and tried using the `params`options for the HTTP call instead of `data`
data: {'params': [143]
}
},
function (error, result) {
// The syntax below should be if not an error, log the result (for testing etc, otherwise, log "http post error". I may have incorrectly switched this around, but the original version I got from an online example had it the console.log statements in the reverse order.
if (!error) {
console.log(result);
} else{
console.log("http post error");
};
});
}
});
I've been using this entry in the Meteor documentation to send the parameters as a JSON object correctly:
http://docs.meteor.com/api/http.html
The connection to Data Domino Lab (DDL) is made correctly, but it doesn't recognize the parameters correctly because the request is not sending the parameters in the JSON format that DDL wants.
result: 'You must provide a JSON object in your request body
with a parameters key containing an array of parameters.' } }
I'm on the DDL free plan, but I will email a link to this question to their tech support. This is a niche issue, but it could be important to Meteor.js developers in the future wishing to link to a data science model in DDL.
I'm one of the engineers at Domino who has worked on the API Endpoints feature recently. The error
message you're getting means that the JSON object you're sending to our server doesn't contain the
key "parameters". I'm not an expert in Meteor, but it looks like you're using "params" where you
should use "parameters" in your JSON payload.
Around line 9 can you change...
{'data': {'params': [143]}}
to
{'data': {'parameters': [143]}}
If my understanding of your code is correct, that'll work correctly.
Cheers!

How do you post to a Web API 2 OData Controller

I created a Web API 2 project and configured an OData4 controller following the steps here: Web API 2 Odata 4 Tutorial
However whenever I try and do a simple POST(with a JSON body to create an entity) using Postman I get the following error back:
The requested resource does not support http method 'POST'.
The POST action in the controller looks like this:
public async Task<IHttpActionResult> Post(Product product)
{
if(!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Products.Add(product);
await db.SaveChangesAsync();
return Created(product);
}
The JSON I am posting in the request body is as follows:
{
"Id":"lewisblack",
"Name":"Lewis",
"Price":"Black",
"Category":"Category 1"
}
And I included the following headers in the request as well:
OData-Version: 4.0
OData-MaxVersion: 4.0
Content-Type: application/json
Am I missing something here?
UPDATE: Figured out the issue. I was using an incorrect URI.
Not much information to go on:
I suspect you don't have a PostMethod on the related controller.
Otherwhise, some other things to think about:
OData is case sensitive
You are missing a property that is required
a datatype is wrong ( Id in the example project is an integer, it looks like a string in your project, Price should be a decimal and not a string, ...)
Whats the HTTP Response code ( if above didn't help), when you post the object. ( use a tool like fiddler). Tip, if your http response is a "bad request", then your data is probably invalid to continue in the action.
I incorrectly used http://localhost:/ for the POST instead of https://localhost:/Products

Grails rest using urlmapper, how to remove class name for rest request

I created a rest server. Using POST method, I send the following data:
{"class":"abc.User","email":"me#gmail.com"}
To make sure it work, I use curl:
curl --request POST --data '{"class":"abc.User","email":"me#gmail.com"}' --header "Content-Type: application/json" http://localhost:8081/abc/api/add
The problem arise when I create rest client to send data. I use rest-client-builder plugin.
My code for client is:
def resp = rest.post("http://localhost:8082/abc/api/add"){
contentType "application/json"
json {
class = "dsi.ewallet.prepaidserver.Kartu"
email = "me#gmail.com"
}
}
I got error: "unexpected token"
If I remove the 'class' , it fix the problem. But my rest server need to pass class name.
Is there anyway to fix it? Or how to remove the need to pass class name for rest server? Thanks.
I think the problem is class is reserved word in java as you can use Class.class or this.getClass(), so it is making problem while parsing, so I think you have to change the name of this attribute.
it is working with curl because it is not using java
I decide to use JSONBuilder()
def builder = new JSONBuilder()
String result = builder.build() {
setProperty("abc", abcValue)
setProperty("def", defValue)
}
return result
When I need to construct more complex structure, I create groovy class that contains only the attributes. Then populate the data to that class and use it with JSONBuilder().

How to send xml/application format in bottle?

If some one come to my url suppose /get it should give back a xml/application format in response in bottle framework. How can i do this? i am using elementree as xml generator.
Look on the official page for the cookie example and do it like this:
#route('/xml')
def xml():
response.headers['Content-Type'] = 'xml/application'
....(create the xml here)......
return xml_content_whatever