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

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.

Related

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;
}

When parsing the constructor GQLReq of type Hasura.GraphQL.Transport.HTTP.Protocol.GQLReq expected Object but got String

I am trying to make a request to a Hasura backend using Flutter, Chopper and Built Value and I am getting the following error
> When parsing the constructor GQLReq of type Hasura.GraphQL.Transport.HTTP.Protocol.GQLReq expected Object but got String.,
Chopper service
#ChopperApi(baseUrl: '/v1/graphql')
abstract class PostApiService extends ChopperService {
#Post()
Future<Response<BuiltPost>> get(#Body() String body);
static PostApiService create(AuthHeaderProvider authHeaderProvider) {
final client = ChopperClient(
baseUrl: 'https://arrivee-app-test.herokuapp.com',
services: [
_$PostApiService(),
],
converter: BuiltValueConverter(),
interceptors: [
HttpLoggingInterceptor(),
// HeadersInterceptor({'content-type': 'application/json'}),
HeadersInterceptor({'Authorization':'Bearer token'})
],
);
return _$PostApiService(client);
}
}
I make request with the following code
var request = RequestModel((b) => b
..query = fetchAccommodations()
..variables = null
..operationName = 'AccommodationGet');
var response = await client.get(request.toJson());
RequestModel
abstract class RequestModel
implements Built<RequestModel, RequestModelBuilder> {
String get query;
#nullable
String get variables;
String get operationName;
RequestModel._();
factory RequestModel([updates(RequestModelBuilder b)]) = _$RequestModel;
String toJson() {
return json
.encode(serializers.serializeWith(RequestModel.serializer, this));
}
static RequestModel fromJson(String jsonString) {
return serializers.deserializeWith(
RequestModel.serializer, json.decode(jsonString));
}
static Serializer<RequestModel> get serializer => _$requestModelSerializer;
}
Encountered the same error while trying to make a simple http POST call to Hasura in Angular Dart (no GraphQL client available).
I have found that the Json String had to be built in the following way :
String query = """
{
account {
id
}
}
""";
Map<String, dynamic> variables;
if (query.trimLeft().split(' ')[0] != 'query') {
query = 'query $docQuery';
}
var jsonMap = {'query': query, 'variables': variables};
final _headers = {'Content-Type': 'application/json'};
return _authHttpService.post(_apiUrl,
headers: _headers, body: json.encode(jsonMap));
Hope it helps anyone looking for a vanilla Dart solution.
I managed to solve it. posting here for future reference.
I let chopper do the conversion from a model to a string instead of doing it manually beforehand here
I changed the signature of the chopper service from :
#Post()
Future<Response<BuiltPost>> get(#Body() String body);
to
#Post()
Future<Response<BuiltPost>> get(#Body() RequestModel body);
and calling the service from:
var request = RequestModel((b) => b
..query = fetchAccommodations()
..variables = null
..operationName = 'AccommodationGet');
var response = await client.get(request.toJson());
to
var request = RequestModel((b) => b
..query = fetchAccommodations()
..variables = null
..operationName = 'AccommodationGet');
var value = await client.get(request);

Looking for the correct syntax for a swagger /document POST from a REST client

I am sending a post to /document (swagger), which should upload a document using the body content of
{
"Application": "tickets",
"File": "some binary data"
}
The back in is using swagger /document so I believe my headers are not coming over correctly.
The problem is I am not getting the correct combination of the headers that need to be sent over:
Authorization : xxxx;
Content-Type : multipart/form-data;
Content-Type : image/png;
Content-Type : application/json;
FileName : file_name
Response:
415 Unsupported Media Type
FileInfo fi = new FileInfo(#"file");
byte[] fileContents = File.ReadAllBytes(fi.FullName);
ByteArrayContent byteArrayContent = new ByteArrayContent(fileContents);
byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
byteArrayContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
FileName = fi.Name,
};
MultipartFormDataContent multiPartContent = new MultipartFormDataContent();
multiPartContent.Add(new StringContent("document storage"), "Application");
multiPartContent.Add(byteArrayContent, "File");
string header = string.Format("WRAP access_token=\"{0}\"", "xxxx");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "/document");
request.Headers.Add("Authorization", header);
request.Content = multiPartContent;
HttpClient httpClient = new HttpClient();
try
{
Task<HttpResponseMessage> httpRequest = httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
HttpResponseMessage httpResponse = httpRequest.Result;
HttpStatusCode statusCode = httpResponse.StatusCode;
HttpContent responseContent = httpResponse.Content;
if (responseContent != null)
{
Task<String> stringContentsTask = responseContent.ReadAsStringAsync();
String stringContents = stringContentsTask.Result;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

Passing a map in GET, JAVA

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
}

How to generate swagger document for akka http web socket route?

How to generate swagger document for akka http web socket route ?
I have able to write akka Http get,put,post,delete. for example
#Path("/postPing")
#ApiOperation(value = "Find a ping", notes = "Returns a pong",
httpMethod = "POST",response = classOf[String])
#ApiImplicitParams(Array(
new ApiImplicitParam(name = "data", value = "\"data\" to sum", required = true,
dataType = "string", paramType = "query"),
new ApiImplicitParam(name = "file", required = true,
dataType = "file", paramType = "query")
))
#ApiResponses(Array(
new ApiResponse(code = 404, message = "websocket not found"),
new ApiResponse(code = 200, message = "websocket found"),
new ApiResponse(code = 400, message = "Invalid websocket supplied")))
def postRoute = path("postPing") {
complete("post pong")
}
But I need for Akka web socket
def webSocketRoute: Route = path("websocket") {
handleWebSocketMessages(broadcast)
}
def broadcast: Flow[Message, Message, Any] = {
Flow[Message].mapConcat {
case tm: TextMessage =>
TextMessage(tm.textStream) :: Nil
}
}
For example
To connect with websocket server
/connect ws://echo.websocket.org/websocket
To send data to websocket server
/send Hello\ world
Thanks in Advance