[HTTP response code]Does one REST API only respond one successful code? - rest

Background:
I'm using Java with Spring boot framework. I have one REST API which input parameter is a int flag, when the flag is 0 then the API will give the response '200' and when the flag is 1 then the response is '204'
[edit]
Now, I can give the response of '200'. But I don't know how to return '200' and '204' by using condition for the REST API.
Question:
Can a REST API return different successful code? If it can, how should I do that?
Thanks.

Spring Boot allows you to customize the HTTP response by editing/creating #RestControllers:
#RestController
public class DoStuffController {
#RequestMapping(value = "/do-stuff", method = RequestMethod.POST)
public void doStuff(#RequestParam int flag, HttpServletResponse response) {
if(flag == 0){
response.setStatus(HttpStatus.OK);
} else {
response.setStatus(HttpStatus.SC_NO_CONTENT);
}
}
}
The above is untested - but should react to a POST /do-stuff?flag=[0|1] by returning eithet HTTP 200 or 204.

Related

Microsoft bot framework: What must a messaging endpoint return?

I am implementing my own messaging endpoint for a MS Teams bot from scratch. I'm almost there. The endpoint does get called with conversationUpdate events, but I see:
There was an error sending this message to your bot: HTTP status code
BadRequest
in the admin on https://dev.botframework.com/bots/channels?id=...
I am probably returning something bad in the HTTP request. As I didn't find anything about the response in the REST API docs, I am just sending the string "{}" with a standard content type.
So what do I actually need to return?
Edit: It appears that the relevant part of the botbuilder-java package is this function in ControllerBase.java:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
Activity activity = getActivity(request);
String authHeader = request.getHeader("Authorization");
adapter.processIncomingActivity(
authHeader, activity, turnContext -> bot.onTurn(turnContext)
).handle((result, exception) -> {
if (exception == null) {
response.setStatus(HttpServletResponse.SC_ACCEPTED);
return null;
}
if (exception.getCause() instanceof AuthenticationException) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
return null;
});
} catch (Exception ex) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
As far as I can tell, this only sets a return code (202) but does not return any content. I now try to do the same thing in my messaging endpoint, but Teams still complains about "BadRequest".
Edit: I have snooped what the actual BotFramework Java sample does - it just returns a code 202 with an empty request body and no content type. I'm now doing the exact same thing, and Teams still complains that it could not send the message. Kinda giving up here.

Call external API using Mule SDK

I am trying to implement a Mule 4.x policy using Mule SDK. In doing so, I need to call an external API in the policy operations implementation. The result returned by the external API response would determine the policy output.
public class MyMulePolicyOperations
{
#MediaType( value = ANY, strict = false )
public void handle(
#Config MyMulePolicyConfiguration configuration,
#Alias( "httpRequestMethod" ) String httpRequestMethod,
CompletionCallback<String, HttpResponse> callback ) throws Exception
{
HttpResponseBuilder httpResponseBuilder = HttpResponse.builder();
String result = // call an external API and extract "result" from the response
if ( result.equals( configuration.getMyConfigValue() ) )
{
httpResponseBuilder.addHeader( "allow_request", "true" );
}
else
{
httpResponseBuilder.addHeader( "allow_request", "false" );
}
Result<String, HttpResponse> result = Result.<String, HttpResponse> builder()
.attributes( httpResponseBuilder.build() )
.build();
callback.success( result );
}
}
Can someone tell me how I can implement the REST client using Mule SDK?
If you want to implement an HTTP request inside a custom module, created with the Mule SDK, then you have to use the HTTP Client as described in the documentation: https://docs.mulesoft.com/mule-sdk/1.1/HTTP-based-connectors#use-the-mule-http-client
You didn't provide any reason or needs to implement the request inside a custom module. It would be way easier just to perform the HTTP request using the HTTP Requester inside the custom policy.

how to get a valid response from a php web service on GWT

I'm trying to get data from a php web service (that I've put in my localhost - tested and works fine) in the client side of my GWT application.
I've tried to use the following package com.google.gwt.http.client.* it looks like the code works fine but the response is always 0, it's highly likely to be a corss problem but I still can't figure how to solve it even though I've tried to use requestBuilder.setHeader(..);
here's the code I'm working on:
String url = "http://localhost/geoTrackerTest.php?id=15";
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
requestBuilder.setHeader("Access-Control-Allow-Origin", "http://localhost");
requestBuilder.setHeader("Access-Control-Allow-Methods", "POST, GET, UPDATE, OPTIONS");
requestBuilder.setHeader("Access-Control-Allow-Headers", "x-http-method-override");
try {
Request request = requestBuilder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
GWT.log("Error: "+exception.getMessage());
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
GWT.log("response: "+response.getText());
} else {
GWT.log("response code: "+response.getStatusCode());
}
}
});
} catch (RequestException e) {
GWT.log("Request Exception: "+e.getMessage());
}
I'm still getting 0 as a response.
You will need to set the header in response from server side (not from the GWT client side), then you can make Cross Site Requests from GWT RequestBuilder. Something like this on server side:
Response.setHeader("Access-Control-Allow-Origin","http://localhost");
If you only need to send GET requests, you can use JSONP (http://www.gwtproject.org/javadoc/latest/com/google/gwt/jsonp/client/JsonpRequestBuilder.html) instead to send cross domain requests, without headers setting on server side.

How to make a rest api call in microsoft bot framework

I need a bot that takes users input, uses it as an id to some third party rest api call and posts back a response. I've looked through Microsoft documentation but didn't find any examples on how to program that request-response process.
Any examples or useful links would be appreciated
Adding to Jason's answer, since you wanted to make a REST api call, take a look at this code :
public class RootDialog : IDialog<object>
{
public Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
return Task.CompletedTask;
}
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var activity = await result as Activity;
// User message
string userMessage = activity.Text;
try
{
using (HttpClient client = new HttpClient())
{
//Assuming that the api takes the user message as a query paramater
string RequestURI = "YOUR_THIRD_PARTY_REST_API_URL?query=" + userMessage ;
HttpResponseMessage responsemMsg = await client.GetAsync(RequestURI);
if (responsemMsg.IsSuccessStatusCode)
{
var apiResponse = await responsemMsg.Content.ReadAsStringAsync();
//Post the API response to bot again
await context.PostAsync($"Response is {apiResponse}");
}
}
}
catch (Exception ex)
{
}
context.Wait(MessageReceivedAsync);
}
}
Once you get the input from user, you can make a REST call and then after you get the response back from API, post it back to the user using the context.PostAsync method.
As Ashwin said, A bot is just a web API and you are just sending/receiving requests as you would with any web API. Below is some documentation that should help get you started.
Basic Overview
Create a bot with the Bot Connector service
API Reference

What i have to return after a DELETE?

I'm wondering what I have to return after that I call my REST API using the DELETE method. I wasn't able to find out any standard/best practice for this. At the moment my code base use 2 different approach, first of all return the deleted resource so into the Response Body I return just null. The second approach (which I don't really like) I instance a new Object and I return it. What you do think is the best way? If none of this two seems good to you, which one would be the best (practice) approach?
Here a sample of what I actually have: code sample
NB: Of course both of the described approach, are performed after the actual deleting on the DB.
After successful deletion you should return empty body and 204 No Content status code.
When returning 200 OK with empty body some clients (e.g. EmberJS) fail because they expect some content to be parsed.
I would return a HTTP 204 OK in order to signal that the request has succeeded.
If you need to return a response body, in case the deletion has triggered something, I would use a HTTP 200 OK with a body attached.
what about Returning void wich means HTTP 200 OK in case of success
#RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public void delete(#PathVariable("id") Long id) {
service.delete(id);
}
EDIT
In the front Controller you can use something like this:
#RequestMapping(...)
public ModelAndView deleteMySlide(Model model,...){
try {
//invoke your webservice Here if success
return new ModelAndView("redirect:/anotherPage?success=true");
} catch (HttpClientErrorException e) {
//if failure
return new ModelAndView("redirect:/anotherPage?success=false");
}
}
or :
#RequestMapping(...)
public String deleteMySlide(Model model,...){
try {
//invoke your webservice Here if success
model.addAttribute("message","sample success");
return "redirect:/successPage");;
} catch (HttpClientErrorException e) {
//if failure
model.addAttribute("message","sample failure");
return "redirect:/failurePage");
}
}