Passing a map in GET, JAVA - rest

How do i Pass a Map of Key Value pairs to a GET REST API,
Here is the call to the resource .. I am getting a method not allowed
String queryMap= String.format("{'softwareversion':'%s','peril':'%s','analysistype':'%s', 'region':'%s'}", "HD18", "Flood", "EP", "USFL");
String url = String.format("http://localhost:%d/templates/modelprofile?queryMap=%s", API_APPLICATION_RULE.getLocalPort(),queryMap);
Response response = ClientBuilder.newClient()
.target(url)
.request()
.header("Authorization", getToken())
.get();
I have the resource as below
#GET
#Path("/{templateType}")
#Timed
#Produces(MediaType.APPLICATION_JSON)
#ApiOperation(value = "Get templates based on peril/region,version and type",
httpMethod = ApiConstants.GET)
#ApiResponses(value = {
#ApiResponse(code = ApiConstants.INT_200,
message = "TemplateReader was retrieved successfully from the database."),
#ApiResponse(code = ApiConstants.INT_400,
message = "Bad request (wrong or missing inputs)"),
#ApiResponse(code = ApiConstants.INT_500,
message = ApiConstants.INTERNAL_SERVER_ERROR)
})
public Template getTemplate(#ApiParam(hidden = true) #Auth User user,
#ApiParam(name = "templateType", value = "templateType")
#PathParam("templateType") String templateType,
#ApiParam(name = "queryMap", value = "queryMap")
#RequestParameters Map<String,String> queryMap
) throws ApiException

You can pass it using request parameter as below.
#RequestMapping(name = "/url/", method = RequestMethod.GET)
public void method_name(#RequestParam(name = "map_name")Map<String, Object> requestMap){
//Process map and perform your logic
}

Related

How to send POST request to another microservice containing enum #RequestParam in kotlin?

I tried to send request to another service containing enum #RequestParam but it always fails.
Here's the example of my request;
fun upsertExclusionOverride(
request: request
): ExcOve? {
val builder = UriComponentsBuilder.fromUriString("/v1/p-b/e/bulk")
val httpEntity = RestTemplateUtils.getHttpEntityCustomHeaders(request, headers)
try {
val body = restTemplate
.exchange(
builder.toUriString(),
HttpMethod.POST,
httpEntity,
Response::class.java
)
.body
?: throw Exception("Fail")
return body.toDomain()
} catch (e: RestClientException) {
log.error(e.message)
throw Exception("Fail")
}
}
This is the other microservice;
#PostMapping("/e/bulk")
#ApiOperation("Exclude")
fun exclusionsInBulk(
#RequestParam(name = "operation", required = true) operation: Operation,
#RequestPart("file") #ApiParam(
value = "File",
required = true,
format = "byte"
) file: MultipartFile
): ResponseEntity<Response> {
.....
}
How should I prevent 400 Bad Request?
I added enum converter but it didn't work.
I expect it to not to get 400 Bad Request.

In Jersey, how to return an object with 400 response code different than the 200 response object

I am new to Jersey and to REST in general, so this might be a stupid question....
In my code, I send a request (TemplateValidationRequest) to try to validate an object. If the object fails to validate, I want to return a String. How do I do this?
In the second code snippet at the bottom, you can see that I'm looking for TemplateValidationResponse object. How can I change my code so that:
I can return a string, and
I can get a String instead of a TemplateValidationResponse object.
Is this possible?
#POST
#Path("validate/modelTemplate")
#Produces({MediaType.APPLICATION_JSON})
#Consumes({MediaType.APPLICATION_JSON})
#Operation(
summary = "Convert model template to AMBOS interaction model and validate the result",
tags = { BLUEPRINTS_TAG },
requestBody = #RequestBody(
content = #Content(
schema = #Schema(
implementation = TemplateValidationRequest.class
)
)
),
responses = {
#ApiResponse(
responseCode = "200",
description = "Success.",
content = #Content(
schema = #Schema(
implementation = TemplateValidationResponse.class
)
)
),
#ApiResponse(
responseCode = "400",
description = "Failure",
content = #Content(
schema = #Schema(
implementation = String.class
)
)
)
}
)
#CustomerIdentityRequired
#AcceptsLanguageRequired
#AAA(serviceName = SERVICE_NAME, operationName = BLUEPRINTS_GET)
ModelTemplateValidationResponse validateModelTemplate(TemplateValidationRequest);
 
fun validateModelTemplate(modelTemplate: InteractionModel,
sampleData: Map<String, Any>): TemplateValidationResponse {
val request = TemplateValidationRequest()
request.modelTemplate = modelTemplate
request.sampleData = sampleData
return temp.validateModelTemplate(request)//this is where I call the above code
//If this request fails and results in a 400 error, I want to get a String
}
What about something like:
public Class YourResponse {
private boolean isError;
private String setThisWhenThereIsError;
private YourObject setThisWhen200;
}

How to post JSON data to Pardot API via Httpclient

I am trying to post the JSON data to Pardot. I have used the info from here to call the Pardot API and currently using Pardot form handler to post the data. I want to know if i could the data via Pardot API call by using CREATE or UPSERT instead of using a form handler.
Below is my code
class SendingDataToPardot
{
public string Login()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var url = "https://pi.pardot.com/api/login/version/3";
string apiKey = null;
var loginInfo = new Dictionary<string, string>
{
{"email", "xx"},
{"password", "xxx"},
{"user_key", "xxx"}
};
var httpContent = new FormUrlEncodedContent(loginInfo);
using (var client = new HttpClient())
{
HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string resultValue = response.Content.ReadAsStringAsync().Result;
apiKey = XDocument.Parse(resultValue).Element("rsp").Element("api_key").Value;
return apiKey;
}
else
{
return null;
}
}
}
public string POST()
{
string Api_Key = Login();
var url = "form handler url";
var contactFormData = new Dictionary<string, string>
{
{"email", "test#test.com"},
{"FirstName", "xxx"},
{"LastName", "xxxxx"},
{"Comments", "this is a test"}
};
var data= new FormUrlEncodedContent(contactFormData);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Api_Key);
HttpResponseMessage response = client.PostAsync(url, data).Result;
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
}
}
}
For most of the APIs Pardot exposes, you need to do XML work with it.
Looks like you are using Java, so you might have luck using a public library, even if just for understanding communication patterns (we had to rewrite it for our purposes, but it did serve as a great blueprint).
Have a look at the https://github.com/Crim/pardot-java-client project and see if it helps you out.

400 Bad Request when posting to Rest API over https

I'm trying to post a file in a json object to an external rest api over https. I have confirmed the json object is formatted correctly, do I have to do anything special to post to a rest api over https? I'm using the answer found over here as a guide: How to post JSON to the server?
private static void PostDatatoFTP(string FileName,
string fileString, string centerCode, string fileType) {
try {
byte[] plainTextBytes = Encoding.ASCII.GetBytes(fileString);
string base64File = Convert.ToBase64String(plainTextBytes);
FileInfo fileInfo = new FileInfo {
FileData = base64File,
FileName = FileName,
FileType = fileType,
FileVersion = _fileVersion
};
FileInfo[] transmitFileInfo = new FileInfo[1];
transmitFileInfo[0] = fileInfo;
Json jsonObject = new Json {
RequestType = _RequestType,
APIVersion = _apiVersion,
SubmissionId = Guid.NewGuid().ToString(),
UserId = _ftpUsername,
Password = _ftpPassword,
Vendor = _vendor,
CenterCode = centerCode,
FileInfo = transmitFileInfo
};
var json = JsonConvert.SerializeObject(jsonObject);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_uploadPath);
request.Method = "POST";
request.ContentType = "application/json";
using (var streamWriter = new StreamWriter(request.GetRequestStream())) {
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream() ?? throw new InvalidOperationException())) {
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
}
catch (WebException e) {
Console.WriteLine(e.Message);
String status = ((HttpWebResponse)e.Response).StatusDescription;
Console.WriteLine(status);
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}

Azure Storage Service throws 403 forbidden error when trying to call REST API to clear queue messages

I'm trying to clear all azure storage queue message via Queue Service REST API. I've verified that the code is correct, but it still returns a 403 forbidden error. The "StorageSharedKey" and "StorageAccountName" are correct since I'm able to connect to the azure queue using those values in the connection string for the azure queue client. The storage version I'm using is "2015-12-11".
Here is the code:
internal void ClearStorageQueueMessages(string queueName)
{
const string requestMethod = "DELETE";
string urlPath = $"{queueName}/messages";
var dateInRfc1123Format = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
var canonicalizedHeaders = $"x-ms-date:{dateInRfc1123Format}\nx-ms-version:{StorageVersion}";
var canonicalizedResource = $"/{StorageAccountName}/{urlPath}";
var uri = new Uri($"https://{StorageAccountName}.queue.core.windows.net/{urlPath}");
var response = MakeDeleteRestCall(uri, requestMethod, dateInRfc1123Format, canonicalizedHeaders, canonicalizedResource);
}
internal RestResponse MakeDeleteRestCall(Uri uri, string requestMethod, string dateInRfc1123Format, string canonicalizedHeaders,
string canonicalizedResource)
{
var restResponse = new RestResponse();
var stringToSign = $"{requestMethod}\n\n\n\n\n\n\n\n\n\n\n\n{canonicalizedHeaders}\n{canonicalizedResource}";
var authorizationHeader = CreateAuthorizationHeader(stringToSign);
var request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = requestMethod;
request.Headers.Add("x-ms-date", dateInRfc1123Format);
request.Headers.Add("x-ms-version", StorageVersion);
request.Headers.Add("Authorization", authorizationHeader);
//request.Accept = "application/atom+xml,application/xml";
request.Accept = "application/json";
//request.ContentType = "application/json";
using (var response = (HttpWebResponse) request.GetResponse())
{
restResponse.StatusCode = response.StatusCode;
var responseStream = response.GetResponseStream();
if (responseStream == null)
return restResponse;
using (var reader = new StreamReader(responseStream))
{
restResponse.ReturnedContent = reader.ReadToEnd();
}
}
return restResponse;
}
internal static string CreateAuthorizationHeader(string canonicalizedString)
{
string signature;
using (var hmacSha256 = new HMACSHA256(Convert.FromBase64String(StorageSharedKey)))
{
var dataToHmac = Encoding.UTF8.GetBytes(canonicalizedString);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
var authorizationHeader = string.Format(CultureInfo.InvariantCulture, "{0} {1}:{2}", StorageSharedKey,
StorageAccountName, signature);
return authorizationHeader;
}
The problem seems to be with the header Authorization. Please check the format according to the documentation:
Authorization="[SharedKey|SharedKeyLite] :"
https://msdn.microsoft.com/en-us/library/azure/dd179428.aspx
Your function adds the shared key in plain text instead of the authorization scheme "SharedKey" or "SharedKeyLite".