I'm on step 2 of an application process. The first step was to use a GET method onto a URL and retrieve a name and email address.
Here is the URL:
https://mkpartners.secure.force.com/services/apexrest/careers?firstName=Homer&lastName=Simpson&email=HSimpson#Springfield
Now I'm being asked to POST a JSON Object. Here is the problem:
Congratulations John Quach, you completed Step 1!
Step 2 is as follows:
Perform a POST to the URL you constructed in Step 1.
You will need to post an instance of the application object described below.
You will need to post the body in properly formatted JSON.
You will need to pass in all required headers.
Please set the isTest boolean to TRUE while testing, and FALSE when you are ready for your final submission.
application {
Boolean isTest (required)
String firstName (required)
String lastName (required)
String email (required)
String phone (required)
String zipcode (required)
String describeYourself (required)
ool[] objectLanguages (required)
education[] education (required)
experience[] experience (required)
certification[] certs
}
education {
String school (required)
Integer graduationYear (required)
String degree (required)
String major (required)
}
experience {
String company (required)
Date fromDate [yyyy-MM-dd] (required)
Date toDate [yyyy-MM-dd] (required)
String title (required)
String workDone (required)
}
certification {
String certification (required)
Date dateCertified [yyyy-MM-dd] (required)
}
ool {
String language (required) [must include at least 'javascript'; include any other OOP languages you know]
Integer proficiency (required) [scale of 0-10, 0 being none, 10 being proficient]
}
A successful post will result in a code 202 and you will receive an automated email confirmation. Good Luck!
I've tried many codes. I've followed your suggestion and used this based on the code you've given. I'm using javascript through an HTML page.
<script>
var webLink = "https://mkpartners.secure.force.com/services/apexrest/careers?firstName=John&lastName=Quach&email=johnq1216#gmail.com";
var apply = {
isTest : false,
firstName : "John",
lastName : "Quach",
email : "johnq1216#gmail.com",
phone : 6269355016,
zipcode : 91207,
describeYourself : "Self Taught Programmer and Developer"
}
function httpPost(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", theUrl, false);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlHttp.send(JSON.stringify(apply));
}
httpPost(webLink);
</script>
//This script will make a POST request. Read above comments.
Of course none of it works. What am I doing wrong? Do I need the complete JSON Object with the Language, Education, and Certification objects nested in? The reason I left them out is because I want to get some response from the website and I wanted to keep the answer small.
Do I need more than just a notepad on my computer to get this JSON object to be posted to the URL?
//You will still have to do the JSON encoding. Use the JSON encoder for this and then make the request. Pass the JSON object you get after processing into http post as a parameter.
<script>
var webLink = "https://mkpartners.secure.force.com/services/apexrest/careers";
var moreSimplified = { firstName : "John", lastName : "Quach", email : "johnq1216#gmail.com" }
function httpPost(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", theUrl, false);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlHttp.send(JSON.stringify(moreSimplified));
}
httpPost(webLink);
</script>
//This script will make a POST request. Read above comments.
Your json is invalid
var json = {
firstName : "John",
lastName : "Quach",
email : "johnq1216#gmail.com"
};
xmlhttp.send(string) work only with POST verb
xmlhttp.open("POST", ,"demo_post.asp",true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify(json);
Related
My access_token contains lot of ...
I need to manually copy only the relevant parts of the access token (without trailing ...) to follow up requests.
How do I parse this access token to variable in postman without trailing ..., because if I put
pm.environment.set("AccessToken", accessToken);
above line in Tests section in postman, then AccessToken variable
Ok I'm able to remove trailing ... from access token via following script in Tests part of request
var response = pm.response.json()
var accessToken = response.access_token;
while(accessToken.charAt(accessToken.length-1) == '.')
{
accessToken = accessToken.substr(0, accessToken.length-1);
}
pm.collectionVariables.set("AccessToken", accessToken);
#DalmTo
Here is how I did it. (I've used the existing collection with minor changes to the script - Sorry I forgot where I got script from)
There are 2 Request in total (only 1st time 2 request, after that you only need to perform 2nd request)
Pre-requisite step
create collection variable privateKey and set its value to your PRIVATE KEY from .json file that you got during Service Account key creation.
eg.
{-----BEGIN PRIVATE KEY-----*****(Complete PRIVATE Key excluding \n from it)****-----END PRIVATE KEY-----
}
Request 1 Script (you only need to run this script once)
GET http://kjur.github.io/jsrsasign/jsrsasign-latest-all-min.js
in this request put following script in Tests section to save jsrsasign-js as collection variable
pm.collectionVariables.set('jsrsasign-js', responseBody);
Request 2 Script (you run this request every time you need token)
POST https://oauth2.googleapis.com/token
Body
x-www-form-urlencoded
grand_type : urn:ietf:params:oauth:grant-type:jwt-bearer
assertion : {{jwt}}
Pre-request Script
var navigator = {};
var window = {};
eval(pm.collectionVariables.get("jsrsasign-js"));
var scope = pm.collectionVariables.get('scope');
var iss = pm.collectionVariables.get('iss');
var privateKey = pm.collectionVariables.get('privateKey');
const header = {"alg" : "RS256", "typ" : "JWT"};
const claimSet =
{
"iss":"service account email",
"sub":"user's email that you requesting token for",
"scope":"https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.events" ,
"aud":"https://oauth2.googleapis.com/token",
"exp":KJUR.jws.IntDate.get("now + 1hour").toString(),
"iat": KJUR.jws.IntDate.get("now").toString()
}
console.log(`header: ${ JSON.stringify(header)}`);
console.log(`claim set: ${ JSON.stringify(claimSet) }`);
var jwt = KJUR.jws.JWS.sign(null, header, claimSet, privateKey);
console.log(jwt);
pm.collectionVariables.set('jwt', jwt);
In the above script, you can change the value of
"sub" : "User's email address" to impersonate that user and get token on their behalf. Also, change "Scope" : " to appropriate scope"
Now when you run the second Request You will get token in response
{
"access_token": "ya29.a0ARr*********",
"expires_in": 3599,
"token_type": "Bearer"
}
You can add this script in Tests section of 2nd Request to parse that token to the collection variable and use that variable for all subsequent requests for Google API
var response = pm.response.json()
var accessToken = response.access_token;
while(accessToken.charAt(accessToken.length-1) == '.')
{
accessToken = accessToken.substr(0, accessToken.length-1);
}
pm.collectionVariables.set("AccessToken", accessToken);
Subsequent requests
GET https://www.googleapis.com/calendar/v3/calendars/calendarID/events
Authorization
Type : Bearer Token
Token : {{AccessToken}}
Clarification
When I'm requesting as particular user's token with "sub": "user's email", Access token that I received does not have trailing .... in them.
I am a beginner to oatpp and building a crud operation demo application. I want to send only two of these four properties (id, name, email, salary) in dto for change email service, in the request payload like below:
{
"id":"1",
"email":"email1"
}
You can do it by either creating a separate DTO containing these two fields and then assign values,
or by returning oatpp::Fields<oatpp::Any>.
Using oatpp::Any
ENDPOINT("GET", "/", myEndpoint) {
oatpp::Fields<oatpp::Any> responseDto = {
{"id", oatpp::Int32(1)}, //<-- put your id here
{"email", oatpp::String("email1")} //<-- put your email here
};
return createDtoResponse(Status::CODE_200, responseDto);
}
result:
{"id":1,"email":"email1"}
I am a newcomer, not a professional coder (so be gentle), trying to build a Flutter app that must connect to a web/server API in HTTP.
According to the doc, to make a connection a header must be used, this header uses the Basic Ath method, with login and password + a content type.
Till that point I think I have found how to do (see code snippet hereunder) but I have to send a user id and a user password to the API in order to receive back user data. And I must humbly confess that I am stuck there...
I thank you in advance for your help!
Bernard
My code (after importing dart:convert et package:http/http.dart + installed the required dependencies) :
void brol() async {
String username = 'user';
String password = 'pass';
String userpass = '$username:$password';
String basicAuth =
'Basic ' + userpass;
print(basicAuth);
Response r = await get('https://www.adresse/login.php',
headers: {'authorization': basicAuth});
}
Many Thanks in advance for your answer,
Bernard
Your credentials should be in base64. You can visit the SO post in the comment.
Your code should be look like this:
main() async {
String username = 'user';
String password = 'pass';
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
print(basicAuth);
Response r = await get('https://www.adresse/login.php',
headers: <String, String>{'authorization': basicAuth});
print(r.statusCode);
print(r.body);
}
See also this blog post.
I am writing a plain post request using spring boot web module, and the fields in my POST request are name, Description and title.
My question is when i use postman or any client to make a POST request to add a new entity, the json keys, name, Description and title are case sensitive, but how can i make the keys case-insensitive. in other words, even when user makes a post request using description instead of Description my application should accept the value and rather not take null since it was not exact match.
Any thoughts are appreciated
You can write function to check your keys are present with case sensitive values or not. In get method you can call method to pick the key.
public String getIgnoreCase(JSONObject obj, String key) {
Iterator<String> itr = obj.keySet().iterator();
while (itr.hasNext()) {
String key1 = itr.next();
if (key1.equalsIgnoreCase(key)) {
return obj.get(key1);
}
}
return null;
}
If u want to keep #RequestBody Item item. then here is solution:
in application.properties:
spring.jackson.mapper.accept_case_insensitive_properties=true
if you use application.yml then:
spring:
jackson:
mapper:
accept_case_insensitive_properties: true
Hi I'm new with moodle and I'm getting an error when calling the webservice.
Currently I'm trying to retrieve a user from moodle with the following function core_user_get_users_by_field and I'm using rest service to do so. I already managed to create a user thus I am authenticated to use the service.
the error that I'm receiving is
Missing required key in single structure: field
The bellow is the code was used to create a User. the issue that I got from the error is that the parameter that I need to send for the post is not formatted well. Does anyone know how to search correctly with this method or any other method.
String token = "token";
String postData = "username=username";
string createRequest = string.Format("http://domain/webservice/rest/server.php?wstoken={0}&wsfunction={1}&moodlewsrestformat=json", token, "core_user_get_users_by_field");
// Call Moodle REST Service
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(createRequest);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
// Encode the parameters as form data:
byte[] formData =
UTF8Encoding.UTF8.GetBytes(postData);
req.ContentLength = formData.Length;
// Write out the form Data to the request:
using (Stream post = req.GetRequestStream())
{
post.Write(formData, 0, formData.Length);
}
// Get the Response
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream resStream = resp.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
string contents = reader.ReadToEnd();
// Deserialize
JavaScriptSerializer serializer = new JavaScriptSerializer();
if (contents.Contains("exception"))
{
// Error
MoodleException moodleError = serializer.Deserialize<MoodleException>(contents);
}
else
{
// Good
}
The webservice core_user_get_users_by_field needs an associative array given as parameter with the following key:values
'field': 'id'
'values': array of integers (must be an array, possibly with just one value)
In PHP it would be, for example:
$parameters = array('field' => 'id', 'values' => array(13));
It means: the user whose 'id' has the value of 13. Of course, you can use other parameters as well: ('field'=>'lastname', 'values'=> array('Smith'))
The parameters you can choose are the fields of the Moodle 'user' table.
Try to build these parameters in your postData variable.
Here's URL that work with my put this url in postman and set http method to post method
hostname/webservice/rest/server.php?wstoken=any_token&wsfunction=core_user_get_users_by_field&field=email&values[0]=h#fci.com
&moodlewsrestformat=json