-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.cpp
More file actions
313 lines (268 loc) · 14.3 KB
/
api_server.cpp
File metadata and controls
313 lines (268 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
#include <iostream> // used for input and output
#include "features/book.hpp"
#include "features/library.hpp"
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <nlohmann/json.hpp>
#include <boost/config.hpp>
#include <memory>
#include <sstream>
#include <string>
#include <thread>
#include <cstdlib>
namespace http = boost::beast::http;
namespace beast = boost::beast;
using json = nlohmann::json;
using namespace std;
Library lib;
vector<Book> library_data;
// SERIALIZING AND DESERIALIZING
json book_to_json(Book& book){ // serializing each book
json j;
j["bid"] = book.get_bid(); //changing to key-value json format (like dictionary)
j["title"] = book.get_title();
j["author"] = book.get_author();
j["category"] = book.get_category();
j["status"] = book.get_status();
return j;
}
json books_to_json(vector<Book>& library){ // serializing the books from cpp to json
json j_arr = json::array();
for(Book& book : library){
json j_book = book_to_json(book);
j_arr.push_back(j_book);
}
return j_arr;
}
Book json_to_book(json& j){ // deserializing each book
int bid = j.contains("bid") ? j["bid"].get<int>() : -1; // .contains("bid") used to check if a value exists or not
string title = j.contains("title") ? j["title"] : "";
string author = j.contains("author") ? j["author"] : "";
string category = j.contains("category") ? j["category"] : "";
string status = j.contains("status") ? j["status"] : "";
Book new_book = Book(bid, title, author, category, status);
return new_book;
}
template<class Body, class Allocator> // similar to a class and will contain funtions for different endpoints(like web pages) also handling different errors
http :: message_generator handle_requests(
http :: request <Body, http :: basic_fields<Allocator>>&& req){ // all requests and funtions go under thiis
auto const bad_request = [&req](beast :: string_view why){
http :: response<http::string_body>res{http::status::bad_request, req.version()}; // body of the response will be a string - status::bad_request will get the status code for that status
res.set(http::field::server, BOOST_BEAST_VERSION_STRING); // set a header value(for response) + version of boost beast in it
res.set(http::field::content_type, "application/json"); // set a header with content type in it
res.keep_alive(req.keep_alive()); // this says that as long as the the request is alive or active the reponse should also be "alive" or active
json error_json; // to store body
error_json["error"] = std::string(why);
res.body() = error_json.dump(); //writing the error_json into the body
res.prepare_payload(); // to say that headers are finalized and the response is ready
return res;
};
auto const not_found = [&req](beast::string_view page){
http :: response<http::string_body>res{http::status::not_found, req.version()};
res.set(http::field::server, BOOST_BEAST_VERSION_STRING); // set a header value(for response) + version of boost beast in it
res.set(http::field::content_type, "application/json"); // set a header with content type in it
res.keep_alive(req.keep_alive()); // this says that as long as the the request is alive or active the reponse should also be "alive" or active
json error_json; // to store body
error_json["error"] = "The resource " + std::string(page) + " is not found";
res.body() = error_json.dump(); //writing the error_json into the body
res.prepare_payload(); // to say that headers are finalized and the response is ready
return res;
};
auto const server_error = [&req](beast::string_view what){
http :: response<http::string_body>res{http::status::internal_server_error, req.version()};
res.set(http::field::server, BOOST_BEAST_VERSION_STRING); // set a header value(for response) + version of boost beast in it
res.set(http::field::content_type, "application/json"); // set a header with content type in it
res.keep_alive(req.keep_alive()); // this says that as long as the the request is alive or active the reponse should also be "alive" or active
json error_json; // to store body
error_json["error"] = "An error occured: " + std::string(what);
res.body() = error_json.dump(); //writing the error_json into the body
res.prepare_payload(); // to say that headers are finalized and the response is ready
return res;
};
auto const success_res = [&req](const json& response_json){
http :: response<http::string_body>res{http::status::ok, req.version()};
res.set(http::field::server, BOOST_BEAST_VERSION_STRING); // set a header value(for response) + version of boost beast in it
res.set(http::field::content_type, "application/json"); // set a header with content type in it
res.keep_alive(req.keep_alive()); // this says that as long as the the request is alive or active the reponse should also be "alive" or active
res.body() = response_json.dump(); //writing the error_json into the body
res.prepare_payload(); // to say that headers are finalized and the response is ready
return res;
};
std::string target = std::string(req.target()); // target includes all endpoints(different url pages)
try{
// SEARCH BOOK FUNCTION
if(req.method() == http::verb::get && target.find("/books/search")==0){ // if the target/endpoint for search book is found- 0 means the endpoint is found
int query_start = target.find("?title="); // position of the title, if present
if (query_start == std::string::npos){ // if there is no title in the the request
return bad_request("missing title");
}
std::string search_title = target.substr(query_start + 7);
vector<Book> sorted_lib = lib.sort_library(library_data, "title");
Book searched_book = lib.search_book(sorted_lib, search_title);
json response;
response["result"] = book_to_json(searched_book);
return success_res(response);
}
// ADD BOOK FUNCTION
if(req.method() == http::verb::post && target.find("/books/add")==0){
try{
json req_json = json::parse(req.body()); // getting the req body, convert it into json and store it
int bid = library_data.size() + 1;
string title = req_json["title"];
string author = req_json["author"];
string category = req_json["category"];
string status = req_json["status"];
bool success = lib.add_book(library_data, bid, title, author, category, status);
if(success){
json response;
response["message"] = "Book added successfully!";
Book new_book = Book(bid, title, author, category, status);
response["book"] = book_to_json(new_book);
return success_res(response);
}
else{
return server_error("Database error when adding book.");
}
}
catch(const exception& e){ // e stores the default error raised in the try block
return bad_request(e.what()); // returning default given error
}
}
//LIST BOOKS FUNCTION
if(req.method() == http::verb::get && target.find("/books/list")==0){ // check endpoint /books/list
// error handling
if(library_data.empty()){
return bad_request("library is empty");
}
//if the library data is not empty, then is has data which we need to list thru a response
json response;
response["message"] = "Library list";
response["books"] = books_to_json(library_data);
return success_res(response);
}
// REMOVE BOOK
if(req.method() == http::verb::delete_ && target.find("/books/remove")==0){
int query_start = target.find("?title="); // position of the book/title to remove, if present
if (query_start == std::string::npos){ // if there is no title in the the request
return bad_request("missing title");
}
std::string remove_title = target.substr(query_start + 7);
Book book_to_delete = lib.search_book(library_data, remove_title); // get the deleted book's object using search func
try{
lib.remove_book(library_data , remove_title);
json response;
response["message"] = "Book removed successfully!";
response["deleted_book"] = book_to_json(book_to_delete); // display the deleted book object
return success_res(response);
}
catch(const exception& e){
return server_error("Database error when removing book."); //internal error
}
}
// SORT LIBRARY
if(req.method() == http::verb::get && target.find("/books/sort")==0){
int query_start = target.find("?by="); // position of the book/title to remove, if present
if (query_start == std::string::npos){ // if there is no title in the the request
return bad_request("missing sort choice");
}
std::string sort_choice = target.substr(query_start + 4);
if(sort_choice != "title" && sort_choice != "author"){
return bad_request("Sort choice has to be by title or author");
}
vector<Book> sorted_lib = lib.sort_library(library_data, sort_choice);
json response;
response["message"] = "Sorted by " + sort_choice;
response["sorted_library"] = books_to_json(sorted_lib);
return success_res(response);
}
}
catch(const exception& e){
return server_error(e.what());
}
}
void fail(beast::err_code ec, string what){
cerr << what << " : " << ec.message() << endl; //printing the error using c err
}
void do_session(tcp::socket& socket) {
beast::error_code ec;
beast::flat_buffer buffer; // making sort of a pipe where the data can flow through and satisfy request
for(;;) { // infinite loop
// Read a request
http::request<http::string_body> req; // reading request
http::read(socket, buffer, req, ec); // makes connection, pipe, reads request + gets error code in case of any error
if(ec == http::error::end_of_stream) // if the error code doesnt occur till the end of the stream
break;
if(ec)
return fail(ec, "read");
// Handle request
http::message_generator msg = handle_requests(std::move(req)); // by move(req) you are shifting the ownership of the request to the hande_requests for it to handle. req cannot be used after this.
// msg example :
/*
HTTP/1.1 200 OK
Server: Boost.Beast/1.80.0
Content-Type: application/json
Content-Length: 123
Connection: keep-alive
{
"books": [
{ "bid":1, "title":"Book A", "author":"Author A" },
{ "bid":2, "title":"Book B", "author":"Author B" }
],
"count": 2
}
*/
// Determine if we should close the connection
bool keep_alive = msg.keep_alive();
// Send the response
beast::write(socket, std::move(msg), ec);
if(ec)
return fail(ec, "write");
if(!keep_alive) {
break;
}
}
// Send a TCP shutdown
socket.shutdown(tcp::socket::shutdown_send, ec);
}
int main(int argc, char* argv[]) {
try {
// Default values
auto const address = net::ip::make_address("0.0.0.0");
auto const port = static_cast<unsigned short>(8080);
if (argc == 3) {
// Custom address and port
auto const custom_address = net::ip::make_address(argv[1]);
auto const custom_port = static_cast<unsigned short>(std::atoi(argv[2]));
// Update address and port variables as needed
}
std::cout << "Loading library from database..." << std::endl;
lib.load_from_db(library_data);
std::cout << "Loaded " << library_data.size() << " books." << std::endl;
// The io_context is required for all I/O
net::io_context ioc{1};
// The acceptor receives incoming connections
tcp::acceptor acceptor{ioc, {address, port}};
std::cout << "Library API Server running on http://" << address << ":" << port << std::endl;
std::cout << "Available endpoints:" << std::endl;
std::cout << " GET /books - List all books" << std::endl;
std::cout << " POST /books - Add a new book" << std::endl;
std::cout << " GET /books/search?title=<title> - Search books" << std::endl;
std::cout << " DELETE /books/<id> - Delete a book by ID" << std::endl;
std::cout << " GET /books/sort?by=<field> - Sort books (title/author)" << std::endl;
std::cout << " POST /books/reload - Reload from database" << std::endl;
for(;;) {
// This will receive the new connection
tcp::socket socket{ioc};
// Block until we get a connection
acceptor.accept(socket);
// Launch the session, transferring ownership of the socket
std::thread{[&socket] { do_session(socket); }}.detach();
}
}
catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
}