CppRestAPI Tutorial 2

Admin私のストア

Last time, we created sql and UserFormat. Next, we will create UserAPI.

After creating the UserAPI, register it on the Router so that it can be called from a URL.

//UserAPI derives from a virtual base class.
template < typename Engine >
class UsersAPI : public virtual Rest API
{
// Run a sql query on the database (MySQL) and in case of select method convert it to a Format class to get the results
using QUERY = Query<Engine, UserFormat>;
//This is a pointer to the class that holds the contents of the sql file.
using SQL = shared_ptr<SQL>;
public:
UserAPI(Engine db, SQL sql)
: db{db}, sql{sql}
{}
// Implement the virtual base class API. All APIs take the ::web::http::http_request argument, which is received using cpprestsdk.
void get(http_request req) override;
void post(http_request req) override;
void put(http_request req) override;
void put(http_request req) override;
private:
Enginedb;
SQL sql;
}
//Let's take the get method as an example.
void UserAPI::get(http_request req) {
Query query{db};
//Execute get_users.sql and get the result as a std::list<UserFormat> type. sql is a closure function object.
auto records = query.select((*sql)("get_users"));
// Save the result in response_json. To create a json array, use the [] operator with a subscript.
::web::json::value response_json;
int i = 0;
for (auto const& record : records) {
response_json[j] = record.json;
i++;
}
// Return the result to the client.
req.reqly(::web::http::status_codes::OK, response_json);
return;
}

Open /CppRestApi/include/server/router.hpp and register the UserAPI in the Router constructor. It will listen for HTTP requests on http://domain/users.

api . insert ( std :: make_pair ( "users" , std :: make_shared < UsersAPI < DB >>(DB{}, sql)));
 
Configure access control.
INSERT INTO api(id, api) VALUES ( 4 , 'users' );
INSERT INTO access(api_id, auth_id, access) VALUES ( 4 , <1|2|3|4> , <true|false>);
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.