oatpp / oatpp

🌱Light and powerful C++ web framework for highly scalable and resource-efficient web application. It's zero-dependency and easy-portable.
https://oatpp.io/
Apache License 2.0
7.62k stars 1.28k forks source link

How to get query parameters? #20

Closed yoshihitoh closed 5 years ago

yoshihitoh commented 5 years ago

Hi there!

I'm interested in to use oat++. oatpp-examples works fine, really good to know how to use oat++! Unfortunately, I couldn't find how to get the query parameters from endpoint defined on ApiController.

I saw that Url class has queryParams, so that I think query parameters are available on oat++. Please let me know how to get that.

Thanks.

lganzzzo commented 5 years ago

Hello @yoshihitoh !

Thank you for the question. I appreciate your interest in the project!

Here is the example endpoint:


  ENDPOINT("GET", "example/path/{path-param}/query/*", getUserWithQueryParams,
           REQUEST(std::shared_ptr<IncomingRequest>, request), // Map request object to endpoint method
           PATH(String, pathParam, "path-param")) {

    /* get url 'tail' - everything that comes after '*' */
    String tail = request->getPathTail(); // everything that goes after '*'

    /* check tail for null */
    OATPP_ASSERT_HTTP(tail, Status::CODE_400, "null query-params");

    /* parse query params from tail */
    auto queryParams = oatpp::network::Url::Parser::parseQueryParams(tail);

    /* get your param by name */
    auto queryParameter = queryParams->get("param"/* parameter name */, "default-value" /* default value */);

    /* return result */
    return createResponse(Status::CODE_200, "path-param=" + pathParam + " query-param=" + queryParameter);

  }

Currently you have to map REQUEST(std::shared_ptr<IncomingRequest>, request) parameter in to your endpoint. So you can get all params of the request.

Curls:

curl -X GET "http://localhost:8000/example/path/2/query?param=hello-world"
path-param=2 query-param=hello-world

curl -X GET "http://localhost:8000/example/path/2/query/?param=hello-world"
path-param=2 query-param=hello-world

Your request will work in both cases with and without '/' before the '*'. But '/' is required before '*' in the endpoint declaration

Regards, Leonid

ghost commented 5 years ago

@lganzzzo Thanks for the detailed explanation! Your code works perfectly. I didn't realize that PathTail means the query string 😀

Many thanks, Yoshihito

lganzzzo commented 5 years ago

You are welcome I am happy to help!

Best Regards, Leonid