Skip to content

ArtaXerxess/NativeAPI

Repository files navigation

API Written in Native C++ Windows OS.

This is basic notes on REST API written on native C++ for Windows machine.

It demonstrates how to create a basic HTTP server that can handle basic GET and POST requests and respond with a simple message.


🛠 Installations

  • Visual Studio 2022 with the "Desktop Development with C++" workload.

  • vcpkg: Clone it and bootstrap it.

    git clone https://github.com/microsoft/vcpkg
    cd vcpkg
    .\bootstrap-vcpkg.bat
  • Install the C++ REST SDK (cpprestsdk):

    .\vcpkg install cpprestsdk:x64-windows

🚀 Step 1: Create a Console Project

  • Open Visual Studio

  • Go to: File -> New -> Project -> Console App

  • Set:

    • Project Name: cpprestapi
    • Location: D:\path\to\dir\cpprestapi

✍️ Step 2: Write Code

Paste the following code into main.cpp:

#include <cpprest/http_listener.h>
#include <cpprest/json.h>
#include <iostream>

using namespace web;
using namespace web::http;
using namespace web::http::experimental::listener;
using namespace web::json;

int main()
{
    uri_builder uri(U("http://localhost:8080"));
    auto addr = uri.to_uri().to_string();
    http_listener listener(addr);

    listener.support(methods::GET, [](http_request request)
    {
        if (request.relative_uri().path() == U("/"))
        {
            json::value response;
            response[U("message")] = json::value::string(U("Hello World from C++ REST API!"));

            http_response resp(status_codes::OK);
            resp.headers().add(U("Access-Control-Allow-Origin"), U("*")); // CORS header
            resp.set_body(response);

            request.reply(resp);
        }
        else
        {
            request.reply(status_codes::NotFound, U("Not Found"));
        }
    });

    try
    {
        listener.open().wait();
        std::wcout << L"Listening at " << addr << std::endl;
        std::wcout << L"Press Enter to Stop" << std::endl;
        std::string line;
        std::getline(std::cin, line); // press Enter to stop
        listener.close().wait();
    }
    catch (std::exception& e)
    {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    return 0;
}

✅ Now you have a basic REST API running at http://localhost:8080 that returns a JSON message on GET /.


Have Fun 😇

Releases

No releases published

Contributors