Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 3672

oat++ guide and 'how to' is obsolete and hard to figure out

$
0
0

Oat++ is a wonderfull library that allow to easily create a web server to implemnet REST service endpoints.However, the docuemntation on their site is not up to date, somtimes refering functions which no longer exists, and their git sample project is too bare boned.I had a real problem trying to figure out how to recieve requst parameters (uri params, path params, and request parameters). And it was really hard to figure out how to recieve a file multipart upload.C++ isn't my main development language so it was very slow going.Since I couldn't find the examples I needed, I'd thought I'd give back to the community by sharing the code sample I made.If there's a better or less involved method of implementing an endpoint for file upload, I'd be glad to see it.

-relevant for oat++ v1.3.0

MyController.cpp:

#ifndef MyController_hpp#define MyController_hpp#include <iostream>#include <fstream>#include "DTOs.h"#include "oatpp/web/server/api/ApiController.hpp"#include "oatpp/macro/codegen.hpp"#include "oatpp/macro/component.hpp"#include "oatpp/web/mime/multipart/InMemoryDataProvider.hpp"#include "oatpp/web/mime/multipart/PartList.hpp"#include "oatpp/data/stream/FileStream.hpp"using std::string;namespace multipart = oatpp::web::mime::multipart;#include OATPP_CODEGEN_BEGIN(ApiController) //<-- Begin Code gen/** * Sample API Controller. */class MyController : public oatpp::web::server::api::ApiController {public:  /**   * Constructor with object mapper.   * @param apiContentMappers - mappers used to serialize/deserialize DTOs.   */    MyController(OATPP_COMPONENT(std::shared_ptr<oatpp::web::mime::ContentMappers>, apiContentMappers))        : oatpp::web::server::api::ApiController(apiContentMappers)    {}public:    // simple GET endpoint, return basic DTO object as JSON. usage: http://localhost:8000/  ENDPOINT("GET", "/", root) {    auto dto = MyDto::createShared();    OATPP_LOGi("ENDPOINT", "GET / Received", "1");    dto->statusCode = 200;    dto->message = "Hello World!!";    dto->address = "test address";    return createDtoResponse(Status::CODE_200, dto);  }  // New endpoint with query parameters. usage: http://localhost:8000/greet?name=John  ENDPOINT("GET", "/greet", greet,      QUERY(String, name, "name")) {      auto dto = MyDto::createShared();      dto->statusCode = 200;      dto->message = "Hello, " + name +"!";      return createDtoResponse(Status::CODE_200, dto);  }  // New endpoint with query parameters. usage: http://localhost:8000/greet/Shemerk  ENDPOINT("GET", "/greet/{name}", greetByName,      PATH(String, name, "name")) {      auto dto = MyDto::createShared();      dto->statusCode = 200;      dto->message = "Hello, " + name +"!";      return createDtoResponse(Status::CODE_200, dto);  }  /* Endpoint that receive request parameters. usage: http://localhost:8000/echo , JSON body:  {"statusCode": 207,"message" : "Hello, Don!","address" : "Baker st 202"  }  */  ENDPOINT("POST", "/echo", echo,      BODY_DTO(Object<MyDto>, requestDto)) {      std::cout << "request dto statusCode: " << requestDto->statusCode <<std::endl;      std::cout << "request dto statusCode: " << requestDto->message.getValue("") << std::endl;      return createDtoResponse(Status::CODE_200, requestDto);  }   // received file uploaded using multipart  ENDPOINT("POST", "/upload", upload,      REQUEST(std::shared_ptr<IncomingRequest>, request)) {      auto multipart = std::make_shared<oatpp::web::mime::multipart::PartList>(request->getHeaders());      oatpp::web::mime::multipart::Reader multipartReader(multipart.get());      multipartReader.setPartReader("file", oatpp::web::mime::multipart::createInMemoryPartReader(10 * 1024 * 1024)); // limit max file size that can be received      request->transferBody(&multipartReader);      auto parts = multipart->getAllParts();            for (const auto &part : parts)      {                if (part->getName() && part->getName() == "file" && part->getFilename())           {                  std::cout << "Handling file: " << part->getFilename()->c_str() << std::endl;                  // Get the input stream for the file                  auto dataStream = part->getPayload()->openInputStream();                  // Read all data into a single buffer                  std::vector<char> buffer;                                 constexpr size_t bufferSize = 4096; // Adjust buffer size as needed                  char tempBuffer[bufferSize];                  size_t bytesRead;                  do {                      bytesRead = dataStream->readSimple(tempBuffer, bufferSize);                      buffer.insert(buffer.end(), tempBuffer, tempBuffer + bytesRead);                  } while (bytesRead > 0);                  // Use 'buffer' containing all data from the file                  // Example: Print the contents to console                  std::cout << "File content:\n" << std::string(buffer.data(), buffer.size()) << std::endl;                     }      }      return createResponse(Status::CODE_200, "OK");  }    // simple file upload and store in local file system (will add headers and footers in the file's body specifying the request details)    ENDPOINT("POST", "/uploadToFile", uploadToFile, REQUEST(std::shared_ptr<IncomingRequest>, request))    {        std::cout << "Upload triggered" << std::endl;        oatpp::data::stream::FileOutputStream fileOutputStream("c:/output/streamed.txt");        request->transferBodyToStream(&fileOutputStream); // transfer body chunk by chunk        return createResponse(Status::CODE_200, "OK");    }};#include OATPP_CODEGEN_END(ApiController) //<-- End Code gen#endif /* MyController_hpp */

DTOs.cpp:

`#ifndef DTOs_hpp#define DTOs_hpp#include "oatpp/macro/codegen.hpp"#include "oatpp/Types.hpp"#include OATPP_CODEGEN_BEGIN(DTO)/***  Data Transfer Object. Object containing fields only.*  Used in API for serialization/de-serialization and validation*/class MyDto : public oatpp::DTO {    DTO_INIT(MyDto, DTO);    DTO_FIELD(Int32, statusCode);     DTO_FIELD(String, message);    DTO_FIELD(String, address);  // declare a new fields in the DTO};#include OATPP_CODEGEN_END(DTO)#endif /* DTOs_hpp */`

Viewing all articles
Browse latest Browse all 3672

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>