Search code examples
flaskhttp-postlibcurlflask-restful

libcurl does not send json-Data


I try to pass some json-Code from c++ to a Python Flask Rest Api. But unfortunatelly this does not work and a don't see my mistake :(

This is my c-Code:

#include <stdio.h>
#include <curl/curl.h>
#include <string>

using namespace std;

int main(void)
{
        CURL *curl;
        CURLcode res;

        curl_global_init(CURL_GLOBAL_ALL);

        curl = curl_easy_init();
        if(curl) {
                curl_easy_setopt(curl, CURLOPT_URL, "localhost:5000/todo/api/v1.0/tasks/debug");
                curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"title\" : \"The Title\"}");

                struct curl_slist *headers = NULL;
                curl_slist_append(headers, "Accept: application/json");
                curl_slist_append(headers, "Content-Type: application/json");
                curl_slist_append(headers, "charsets: utf-8");

                curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
                curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

                res = curl_easy_perform(curl);

                if(res != CURLE_OK)
                        fprintf(stderr, "curl_easy_perform() failed: %s\n",
                                        curl_easy_strerror(res));

                curl_easy_cleanup(curl);
        }
        curl_global_cleanup();
        return 0;
}

This is the flask-function:

#POST DEBUG
@app.route("/todo/api/v1.0/tasks/debug", methods=['POST'])
def echo():
        print(request.json)
        return "ReturnString \n"

The output of the flask-Server looks like this:

None
127.0.0.1 - - [12/Jul/2017 12:49:15] "POST /todo/api/v1.0/tasks/debug HTTP/1.1" 200 -

So it seems to me that the json-Data is not passed to the flask-function. I tried basically the same with text and it worked.

When I try the same thing with a curl-Call from the command-line, it works. Curl-Command:

curl -i -H "Content-Type: application/json" -X POST -d '{"title":"Read a book"}' http://localhost:5000/todo/api/v1.0/tasks/debug

Output from Flask-Server:

{'title': 'Read a book'}
127.0.0.1 - - [12/Jul/2017 13:11:54] "POST /todo/api/v1.0/tasks/debug HTTP/1.1" 200 -

Any Help ?


Solution

  • After I ran your code and looked at the HTTP request with Wireshark, I found that the Content-Type header was not set to application/json. I then compared your code to the one produced by curl ... --libcurl example.c and found that request headers have to be added like so:

    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "Accept: application/json");
    headers = curl_slist_append(headers, "Content-Type: application/json");
    headers = curl_slist_append(headers, "charsets: utf-8");