Box.com create/update folder from salesforce using api v2 - api

I am trying to create a new folder in the Box from a controller class in salesforce using the api version 2. I am receiving the access token and i am also been able to retrieve the items of a folder with a HTTP GET request.
But I am not able to create a new folder in BOX. Also not able to copy files from 1 folder to another or update information about a folder.
Below is the code to update the Description of my folder:
Http h = new Http();
HttpRequest req = new HttpRequest();
string endPointValue = 'https://api.box.com/2.0/folders/myfolder_id';
req.setEndpoint(endPointValue);
req.setHeader('Authorization', 'Bearer ' + myaccessToken);
req.setBody('description=' + EncodingUtil.urlEncode('New', 'U`enter code here`TF-8'));
req.setMethod('POST');
HttpResponse res = h.send(req);
I am getting the following response:
{"type":"error","status":400,"code":"bad_request","context_info":{"errors":[{"reason":"invalid_parameter","name":"entity-body","message":"Invalid value 'description=New'. Entity body should be a correctly nested resource attribute name\/value pair"}]},"help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Bad Request","request_id":"my request Id"}
Can anyone help me on this?
Thanks in advance!

According to documentation here, Box API expects request parameters in JSON format and request method has to be PUT. Try following:
Http h = new Http();
HttpRequest req = new HttpRequest();
string endPointValue = 'https://api.box.com/2.0/folders/myfolder_id';
req.setEndpoint(endPointValue);
req.setHeader('Authorization', 'Bearer ' + myaccessToken);
req.setBody('{"description" : "New folder description"}');
req.setMethod('PUT');
HttpResponse res = h.send(req);
P.S. you were also using EncodingUtil.urlEncode() method incorrectly. First parameter should be a string you are trying to make URL-safe and second parameter is encoding (see documentation here)

Related

How to pull data from CATSone API with Authentication Token?

I am completely new to coding. I am trying to build a dashboard in Klipfolio. I am using a CATSone API to pull data from CATSone to Klipfolio. However, I can only get 100 rows a time, which means I would have to pull data 2600 times.
I am now trying to build a script to get data from the API through Google Script Editor. However, since I have no experience in this, I am just trying stuff. I watched some videos, also from Ben Collins. The basis is simple, and I get what he is doing.
However, I have a problem with putting the API key.
var API_KEY = 'key'
function callCATSone(){
//Call the CATSone API for all candidate list
var response = UrlFetchApp.fetch("https://api.catsone.nl/v3/candidates");
Logger.log(response.getContentText());
// URL and params for the API
var url = 'https://api.catsone.nl/v3/candidates';
var params = {
'method': 'GET',
'muteHttpExceptions': true,
'headers': {
'Authorization': 'key ' + apikey
}
};
// call the API
var response = UrlFetchApp.fetch(url, params);
var data = response.getContentText();
var json = JSON.parse(data);
}
In the end, I would like to transfer all candidate list data to my sheets. Therefore, I call on the API with Authorization key. After that, I will manipulate the data, but that's for later. The first problem I now encounter, is this fail code:
'Verzoek voor https://api.catsone.nl/v3/candidates is mislukt. Foutcode: 401. Ingekorte serverreactie: {"message":"Invalid credentials."} (Gebruik de optie muteHttpExceptions om de volledige reactie te onderzoeken.) (regel 6, bestand 'Code')'.
I expect to get a list of all data from CATSone into my sheets.
Does anyone know how I can accomplish this?
Two changes should fix the credentials error:
Authorization header should be Authorization: 'Token ' + yourApiKey instead of 'key ', see the v3 API documentation https://docs.catsone.com/api/v3/#authentication.
API key in your case is stored in a global variable API_KEY, you should reference it exactly like that, not as an apikey (unless there is a typo in your sample or some missing code): Authorization : 'Token ' + API_KEY.
Btw, it should probably set either a Content-Type header or a contentType parameter for UrlFetchApp.fetch() method call to application/json as UrlFetchApp.fetch() request content type defaults to application/x-www-form-urlencoded.
If you plan to continue working with APIs, it would be beneficial to read this MDN article.

What should be the java code for rest-assured api for getting the access token

I want to get access token from the given REST-API call.
I have tested this in postman and it is working fine which needs data to be entered in all 3 tabs( Authorization, Header and body and need to fire post method). Please find the attached screenshots for better clarity.
Please guide me how to automate this with java and jayaway restassured library or any other solution.
Postman screenshot- Authorization tab
Postman Screenshot - Header tab
Postman screenshot- Body tab
Note: Username and password is different in Authorization and in different in Body tab
RestAssured.baseURI = "http://URI";
Response res = given().header("Content-Type", "application/json")
.body("{" + " \"username\":\"yourmail#something.com\"," + " \"password\":\"ab#1234\""
+ "}")
.when().post("/api/token").then().log().all().assertThat().statusCode(200)
.contentType(ContentType.JSON).extract().response();
String responseString = res.asString();
System.out.println(responseString);
JsonPath js = new JsonPath(responseString);
String str = js.get("data.access_token");
System.out.println(str);
Assuming that your response will look like this:
{"token_type":"bearer","access_token":"AAAA%2FAAA%3DAAAAAAAA"}
You can try following Rest Assured example:
JsonPath jsonPath = RestAssured.given()
.auth().preemptive().basic("username", "password")
.contentType("application/x-www-form-urlencoded")
.formParam("username", "johndoe")
.formParam("password", "12345678")
.formParam("grant_type", "password")
.formParam("scope", "open_d")
.when()
.post("http://www.example.com/oauth2/token")
.then()
.statusCode(200)
.contentType("application/json")
.extract().jsonPath();
String tokenType = jsonPath.getString("token_type");
String accessToken = jsonPath.getString("access_token");

Pentaho Carte Rest Services giving 302

I am trying to evaluate Carte and add a job I created in the Spoon designer to a local file repository I also created.
I created the xml to add the job and wrote a test program.
The response however is always 302 - any idea how I can get past that to actually call the service ?
I have read that 302 means redirect so go grab the 'Location' header and make another call. In this case the location header again is "http://localhost:8181/kettle/addJob", and re-calling results in a further http 302 response. I seem to be stuck in a loop now ..
String fileName = "C:\\format.xml";
String url = "http://localhost:8181/kettle/addJob";
HttpClient httpClient = new HttpClient();
List authPrefs = new ArrayList();
authPrefs.add(AuthPolicy.BASIC);
httpClient.getParams().setParameter(
AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
Credentials creds = new UsernamePasswordCredentials("cluster",
"cluster");
AuthScope scope = new AuthScope("localhost", AuthScope.ANY_PORT);
httpClient.getState().setCredentials(scope, creds);
AuthPolicy.registerAuthScheme("Basic", BasicScheme.class);
PostMethod post = new PostMethod(url);
String xml = FileUtils.readFileToString(new File(fileName));
post.setRequestBody(xml);
int result = httpClient.executeMethod(post);

Wicket 6 - Capturing HttpServletRequest parameters in Multipart form?

USing Wicket 6.17 and servlet 2.5, I have a form that allows file upload, and also has ReCaptcha (using Recaptcha4j). When the form has ReCaptcha without file upload, it works properly using the code:
final HttpServletRequest servletRequest = (HttpServletRequest ) ((WebRequest) getRequest()).getContainerRequest();
final String remoteAddress = servletRequest.getRemoteAddr();
final String challengeField = servletRequest.getParameter("recaptcha_challenge_field");
final String responseField = servletRequest.getParameter("recaptcha_response_field");
to get the challenge and response fields so that they can be validated.
This doesn't work when the form has the file upload because the form must be multipart for the upload to work, and so when I try to get the parameters in that fashion, it fails.
I have pursued trying to get the parameters differently using ServletFileUpload:
ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory(new FileCleaner()) );
String response = IOUtils.toString(servletRequest.getInputStream());
and
ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory(new FileCleaner()) );
List<FileItem> requests = fileUpload.parseRequest(servletRequest);
both of which always return empty.
Using Chrome's network console, I see the values that I'm looking for in the Request Payload, so I know that they are there somewhere.
Any advice on why the requests are coming back empty and how to find them would be greatly appreciated.
Update: I have also tried making the ReCaptcha component multipart and left out the file upload. The result is still the same that the response is empty, leaving me with the original conclusion about multipart form submission being the problem.
Thanks to the Wicket In Action book, I have found the solution:
MultipartServletWebRequest multiPartRequest = webRequest.newMultipartWebRequest(getMaxSize(), "ignored");
// multiPartRequest.parseFileParts(); // this is needed since Wicket 6.19.0+
IRequestParameters params = multiPartRequest.getRequestParameters();
allows me to read the values now using the getParameterValue() method.

Setting RequestHeaders for Get REST API in Visual Basic

I have located some sample source code in visual basic to call a REST API. However, I need to modify the code by adding two request headers.
' Create the web request
request = DirectCast(WebRequest.Create(sURI), HttpWebRequest)
'Update request headers with request pairs Header1/"header1 value" and header2/"header2 value"
??? HttpWebRequest.headers.Add ????
' Get response
response = DirectCast(request.GetResponse(), HttpWebResponse)
' Get the response stream into a reader
reader = New StreamReader(response.GetResponseStream())
Any help would be appreciated. Thanks!
Many of the normal headers are "built-in," like so:
HttpWebRequest.ContentType = "application/x-www-form-urlencoded"
Alternatively, you should be able to set any header you like with:
HttpWebRequest.Headers("Header1") = "Header1 value"
And another method in line with your original code:
HttpWebRequest.Headers.Add("Header1", "Header1 value")
You could consider using System.Net.WebClient.
Here is some code in C#
using (System.Net.WebClient client = new System.Net.WebClient())
{
string userInfo = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("user:password"));
client.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " + userInfo;
client.DownloadString(url)
}