POST request with data - grails

This might be a noob question but i've been fiddling with it for hours now and wasn't able to find the solution.
I would like to send a POST request with form data using grails,
in jQuery this following 1 liner works as I wish:
$.post('<SOME SERVER URI>', {param1: 'p1'}, function(data) {console.log(data);})
but the following Grails code doesn't:
import static groovyx.net.http.ContentType.JSON
import static groovyx.net.http.Method.POST
import groovyx.net.http.HTTPBuilder
...
def http = new HTTPBuilder(<SERVER BASE URI>)
http.request(POST, JSON) {
uri.path = <REST OF URI>
uri.query = [param1: 'p1']
response.success = { resp, json ->
println 'success'
}
}
I think it has something to do with the data being sent, as the request leaves but fails (facebook graph is the base uri...)
the jquery code sends the data as form data, but i'm not sure thats the problem
Thanks!

It seems that facebook are really stickt on the params, and by sending 2 extra params facebook would not process the request, and simply return 400.
Thanks so much!

Related

cannot authorize using Rest-Assured

400 error cannot understand where is mistake in code
I used Rest-assured documentation
https://www.toolsqa.com/rest-assured/post-request-using-rest-assured/
Please help with this question
package forth;
import org.apache.log4j.BasicConfigurator;
import org.testng.annotations.Test;
import org.testng.Assert;
import io.restassured.RestAssured;
import io.restassured.specification.RequestSpecification;
import io.restassured.response.Response;
import org.json.simple.JSONObject;
public class zero {
#Test
public void RegistrationSuccessful()
{
BasicConfigurator.configure();
RestAssured.baseURI ="url";
RequestSpecification request = RestAssured.given();
JSONObject requestParams = new JSONObject();
requestParams.put("useremail", "my login");
requestParams.put("api_token", "my token");
request.header("Content-Type", "application/json");
request.body(requestParams.toJSONString());
Response response = request.post("/rest/auth/1/session");
int statusCode = response.getStatusCode();
Assert.assertEquals(statusCode, "201");
String successCode = response.jsonPath().get("SuccessCode");
Assert.assertEquals( "Correct Success code was returned", successCode, "OPERATION_SUCCESS");
}
}
First of all, always try opening the end point url in new tab of browser, if it doesn't give any error then, it is an indication that we can use it. If browser displays something like "This site can't be reached", then it is not a valid end point or server is not up and running for respective end point.
In case of toolsqa website, in starting few pages endpoints are not working. I sent a message to Virender to look into this issue, but unfortunately no response.
I suggest you to learn rest assured from makeseleniumeasy website as per my personal experience.
Its very important to check if the api requires form params or body params.
form-params are intended to be used with content-type "application/x-www-form-urlencoded" (a form)
body-params are intended to use for parameters which are also going to be located in the body with other content-types (application/json)

GRAILS URL parameters short form

I know that in GRAILS/GROOVY
def content=urlrestservicestring.toURL().getBytes(requestProperties: ['User-Accepted': username])
is a short form to have all the byte content (for example for PDF donwload), but I don't know all the request properties available for URL for richer connections, for example for POST method (this is a GET call) with payload in json. Is it possible? In which way?
It looks like per requestProperties you can set request headers only which might help for simple cases.
On the other hand if you want to do something more complex, like a POST, you have to use a propper HTTP-client.
In Groovy there's an idiomatic HTTPBuilder which is very straight-forward and easy to use, or Grails own RESTBuilder
UPDATE:
Using HTTPBuilder the download could look like:
import static groovyx.net.http.HttpBuilder.configure
configure {
request.uri = "http://example.org/download"
request.contentType = 'application/json'
}.post {
request.headers.username = 'Scarpanti'
request.body = [ some:'json' ]
Download.toStream delegate, response.outputStream // from grails
// or
// Download.toStream delegate, file
}
see also ref-doc

Open new ticket in JIRA using REST api

I'd like to understand how to create a new ticket in JIRA using REST API from Jenkins. Is there any limitations or special things I should be aware of?
I'm going to write a Python script, which will parse the build log and then create a new ticket in JIRA project.
I checked the plugins, but most of them only can update the existing tickets.
Thanks
There's documentation here about the JSON schema and some example JSON which needs to go in the body of your POST request to /rest/api/2/issue
https://docs.atlassian.com/jira/REST/cloud/#api/2/issue-createIssue
Here's a basic python3 script to make a post request
import requests, json
from requests.auth import HTTPBasicAuth
base_url = "myjira.example.com" # The base_url of the Jira insance.
auth_user = "simon" # Jira Username
auth_pass = "N0tMyRe3lP4ssw0rd" # Jira Password
url = "https://{}/rest/api/2/issue".format(base_url)
# Set issue fields in python dictionary. See docs and comment below regarding available fields
fields = {
"summary": "something is wrong"
}
payload = {"fields": fields}
headers = {"Content-Type": "application/json"}
response = requests.post(
url,
auth=(auth_user, auth_pass),
headers=headers,
data=json.dumps(payload))
print("POST {}".format(url))
print("Response {}: {}".format(response.status_code, response.reason))
_json = json.loads(response.text)
Using this HTTP requests library for python http://docs.python-requests.org/en/master/
You can make a GET request to /rest/api/2/issue/{issueIdOrKey}/editmeta using the id or key of existing issue in the same project as the issue's you will be creating via the API will go to in order to get a list of all the fields you can set and which ones are required.
https://docs.atlassian.com/jira/REST/cloud/#api/2/issue-getEditIssueMeta

ios swift 2.1 - unable to send Patch request with body

I'm trying to write a http rest client for my webservice and i need to send some PATCH requestes with data in the body.
I'm using the JUST library for sending requests ( https://github.com/JustHTTP/Just )
My express application just doesn't see the request.
Here's some code (i'm testing in playground, and everything went fine with other kind of requests like put, post...)
headers = ["accept":"application/json","content-type":"application/json","authorization":"key"] //key is ok
var data = ["id":3, "quantity":6]
var r = Just.patch("http://api.marketcloud.it/v0/carts/1233", headers:headers, data:data) //1233 is a cart Id
print(r)
print(r.json)
The method Just.patch returns an HTTPResult Object.
this says 'OPTIONS http://api.marketcloud.it/v0/carts/13234 200'
Also this object should contain a json, but it's 'nil'.
On the server-side, my express applications doesn't receive the request (it just logs an 'OPTION', but nothing else).
Could this be a playground-related problem? Or a just-related one?
Thanks for any suggestion
I managed to contact the library's author via twitter and he fixed the bug and answered me in less than 24h!
Here's the new release of the library.
https://github.com/JustHTTP/Just/releases

How to create a bigquery table and import from cloud storage using the ruby api

Im trying to create a table on BigQuery - I have a single dataset and need to use the api to add a table and import data (json.tar.gz) from cloud storage. I need to be able to use the ruby client to automate the whole process. I have two questions:
I have read the docs and tried to get it to upload (code below) and have not been successful and have absolutely no idea what Im doing wrong. Could somebody please enlighten me or point me in the right direction?
Once I make the request, how do I know when the job has actually finished? From the API, I presume Im meant to use a jobs.get request? Having not completed the first part I have been unable to get to look at this aspect.
This is my code below.
config= {
'configuration'=> {
'load'=> {
'sourceUris'=> ["gs://person-bucket/person_json.tar.gz"],
'schema'=> {
'fields'=> [
{ 'name'=>'person_id', 'type'=>'integer' },
{ 'name'=> 'person_name', 'type'=>'string' },
{ 'name'=> 'logged_in_at', 'type'=>'timestamp' },
]
},
'destinationTable'=> {
'projectId'=> "XXXXXXXXX",
'datasetId'=> "personDataset",
'tableId'=> "person"
},
'createDisposition' => 'CREATE_IF_NEEDED',
'maxBadRecords'=> 10,
}
},
'jobReference'=>{'projectId'=>XXXXXXXXX}
}
multipart_boundary="xxx"
body = "--#{multipart_boundary}\n"
body += "Content-Type: application/json; charset=UTF-8\n\n"
body += "#{config.to_json}\n"
body += "--#{multipart_boundary}\n"
body +="Content-Type: application/octet-stream\n\n"
body += "--#{multipart_boundary}--\n"
param_hash = {:api_method=> bigquery.jobs.insert }
param_hash[:parameters] = {'projectId' => 'XXXXXXXX'}
param_hash[:body] = body
param_hash[:headers] = {'Content-Type' => "multipart/related; boundary=#{multipart_boundary}"}
result = #client.execute(param_hash)
puts JSON.parse(result.response.header)
I get the following error:
{"error"=>{"errors"=>[{"domain"=>"global", "reason"=>"wrongUrlForUpload", "message"=>"Uploads must be sent to the upload URL. Re-send this request to https://www.googleapis.com/upload/bigquery/v2/projects/XXXXXXXX/jobs"}], "code"=>400, "message"=>"Uploads must be sent to the upload URL. Re-send this request to https://www.googleapis.com/upload/bigquery/v2/projects/XXXXXXXX/jobs"}}
From the request header, it appears to be going to the same URI the error says it should go to, and I am quite at a loss for how to proceed. Any help would be much appreciated.
Thank you and have a great day!
Since this is a "media upload" request, there is a slightly different protocol for making the request. The ruby doc here http://rubydoc.info/github/google/google-api-ruby-client/file/README.md#Media_Upload describes it in more detail. I'd use resumable upload rather than multipart because it is simpler.
Yes, as you suspected, the way to know when it is done is to do a jobs.get() to look up the status of the running job. The job id will be returned in the response from jobs.insert(). If you want more control, you can pass your own job id, so that in the event that the jobs.insert() call returns an error you can find out whether the job actually started.
Thank you for that. Answer resolved. Please see here :
How to import a json from a file on cloud storage to Bigquery
I think that the line of code in the docs for the resumable uploads section (http://rubydoc.info/github/google/google-api-ruby-client/file/README.md#Media_Upload) should read:
result = client.execute(:api_method => drive.files.insert,
Otherwise, this line will throw an error with 'result' undefined:
upload = result.resumable_upload

Resources