oatpp / example-async-api

Example project how-to use oatpp asynchronous API.

Home Page:https://oatpp.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to set application type as application/json when using ENDPOINT_ASYNC?

puneetugru opened this issue · comments

Hi Leonid,

I'm using ENDPOINT_ASYNC to support APIs in the project, like an example below.

ENDPOINT_ASYNC("POST", "{path-param}/rangedata", getRangeData) {

       ENDPOINT_ASYNC_INIT(getRangeData)
       String pathParam;

       Action act() override {
            pathParam = request->getPathVariable("path-param");
            return request->readBodyToDtoAsync<RangeRequestDto>(controller->getDefaultObjectMapper())
               .callbackTo(&getRangeData::onBodyObtained);
       }

       Action onBodyObtained(const RangeRequestDto::ObjectWrapper& requestDto) {    
               
           OATPP_LOGD("MyApp", "Received clientId value=%s", pathParam->std_str().c_str());
           OATPP_LOGD("MyApp", "Received value for sensorID=%s", requestDto->sensorID->std_str().c_str());

           std::string sensorName = "sensor:";
           sensorName += requestDto->sensorID->std_str();

           /*Get the data from Redis Instance*/
           auto redisConnection = RedisHandler::getInstance();
           std::vector<float>valueList; 
           redisConnection->redisZRANGE(sensorName, 0, std::stoi(requestDto->timeRange->std_str()), valueList);
           auto responseDto = RangeResponseDto::createShared();
           if(valueList.size()>0)
           {
            for(auto i: valueList)
                responseDto->readings->pushBack(i);
           }    
           /* return result */
           return _return(controller->createDtoResponse(Status::CODE_201, responseDto));
      }   

};

Here, valueList is filled with string values, which is temperature reading from a sensor.

The values are then pushed in to the readings list of the DTO.

The DTO for the same is as below,

class RangeResponseDto : public oatpp::data::mapping::type::Object {

DTO_INIT(RangeResponseDto, Object /* Extends */)

DTO_FIELD(List::ObjectWrapper, readings) = List::createShared();

};

I would like to know how to set application type as JSON in the header for this response.

  • Thanks,
    Puneet

The data is sent in JSON format, the issue was with the server.

Hello @puneetugru ,

As far as you use controller->createDtoResponse(Status::CODE_201, responseDto) and your default object mapper for the controller is set to oatpp::parser::json::mapping::ObjectMapper - it should already include Content-Type: application/json in the response headers.


In case you want to add some custom headers:

auto response = controller->createDtoResponse(Status::CODE_201, responseDto);
response-> putHeader("X-My-Header", "My-Value");
return _return(response);

Best Regards,
Leonid