0

I have a backend on Flask.
I created API call for uploading file and JSON data.
I created a function for testing this API call that doesn't work too.
I can't find how to send request with file and JSON data. Everything that I tried is failed and didn't enter to the page on backend.
I need your help to find the examples to make the request in C# .NET and python.
Test function:
def test_upload_deidentified_file(self, client, headers):
    url = '/upload_deidentified_file'
    file_path = f"{os.path.dirname(os.path.abspath(__file__))}/../../../../files/test_file.mkv"
    with open(file_path, 'rb') as file:
        data = {
            "filename": "test_file.mkv",
            "campaign_name": "Test Campaign Name",
            "session_id": "12345678-1234-1234-1234-123456789123",
            "activity_id": "12345678-1234-1234-1234-123456789123",
            "tags": ["video"],
            "machine_name": "Test Machine Name",
            "creation_date": "2021-01-01",
        }
        file_data = FileStorage(stream=file, filename='test_file.mkv')
        response = client.post(url,
                               data={'json_data': json.dumps(data),
                                     'file': file_data},
                               headers=headers)
    json_data = response.get_json(silent=True)
    logger.info(f"json_data: {json_data}")
    assert response.status_code == HTTPStatus.OK
    assert isinstance(json_data, dict)

Backend:

app = Flask(__name__)
storage_folder = r"path_to_the_storage_folder"


@app.before_request
def before_request():
    message = {
        "remote_address": request.remote_addr,
        "path": request.path,
        "request_method": request.method,
        "headers": request.headers,
        "data": request.data if request.data else None,
        "args": request.args if request.args else None,
        "form": request.form if request.form else None,
        "json": request.json if request.json else None,
    }
    logger.debug(f"Request: {message}")


@app.after_request
def after_request(response):
    message = {
        "remote_address": request.remote_addr,
        "path": request.path,
        "request_method": request.method,
        "status": response.status,
        "response_data": response.data
    }
    logger.debug(f"Response: {message}")
    return response


@app.route('/upload_deidentified_file', methods=['POST'])
def upload_file():
    logger.info('Upload file request received.')
    # Get the video file from the request
    form_data = request.form
    logger.info('Form data: {}'.format(form_data))
    file = request.files['file']
    logger.info('File: {}'.format(file))
    return 'OK'


if __name__ == '__main__':
    app.run()

Code that I tried:
C# .NET:

// JSON data
var jsonData = new
{
    filename = "test_file.mkv",
    campaign_name = "Test Project Name",
    session_id = "12345678-1234-1234-1234-123456789123",
    activity_id = "12345678-1234-1234-1234-123456789123",
    tags = new List<string> { "video" },
    machine_name = "Test machine name",
    creation_date = "2021-01-01"
};

using (var httpClient = new HttpClient())
{
    if (headers != null)
    {
        foreach (var header in headers)
        {
            httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
        }
    }

    using (var multipartContent = new MultipartFormDataContent())
    {
        // Add the file
        var fileStream = File.OpenRead(local_path_for_tests);
        var fileContent = new StreamContent(fileStream);
        multipartContent.Add(fileContent, "file", Path.GetFileName(local_path_for_tests));

        // Add the JSON data
        var jsonContent = new StringContent(JsonConvert.SerializeObject(jsonData));
        jsonContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        multipartContent.Add(jsonContent, "json");

        // Send the request
        using (var response = await httpClient.PostAsync(server_url, multipartContent))
        {
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
    }
}

Error:

Exception has occurred: CLR/System.Net.Http.HttpRequestException
An exception of type 'System.Net.Http.HttpRequestException' occurred in System.Net.Http.dll but was not handled in user code: 'Response status code does not indicate success: 415 (UNSUPPORTED MEDIA TYPE).'

Python example 1:

# JSON data
data = {
    'filename': 'test_file.mkv',
    'session_id': session_id,
    'campaign_name': "Test Project Name",
    'activity_id': activity_id,
    'tags': ["video"],
    'machine_name': "Test machine name",
    'creation_date': '2021-01-01'
}

files = {
    'file': open(file_path, 'rb')
}

logger.info(f"Sending request to {url} with data: {data} and file: {files['file'].name}")
start = datetime.now()
response = requests.post(url, data=data, files=files)
logger.info(f"Request time: {datetime.now() - start}")
logger.info(f"Response: {response.text}\n")

Error:

<!doctype html>
<html lang=en>
<title>415 Unsupported Media Type</title>
<h1>Unsupported Media Type</h1>
<p>Did not attempt to load JSON data because the request Content-Type was not &#39;application/json&#39;.</p>

Python example 2:

# JSON data
data = {
    'filename': 'test_file.mkv',
    'session_id': session_id,
    'campaign_name': "Test Project Name",
    'activity_id': activity_id,
    'tags': ["video"],
    'machine_name': "Test machine name",
    'creation_date': '2021-01-01'
}

files = {
    'file': open(file_path, 'rb')
}

headers = {
    'Content-Type': 'application/json'
}

json_data = json.dumps(data)

logger.info(f"Sending request to {url} with data: {data} and file: {files['file'].name}")
start = datetime.now()
response = requests.post(url, headers=headers, data=json_data, files=files)
logger.info(f"Request time: {datetime.now() - start}")
logger.info(f"Response: {response.text}\n")

Error:

ValueError: Data must not be a string.

1 Answer 1

0

The HTTP 415 Unsupported Media Type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format.The format problem might be due to the request's indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly. Refer this

For the problem you are facing, please check the content header, encoding utf-8 is missing and which resulted in 415 in your Python example 1. Request you include both the content-type and content-encoding both in the request header. Let me know the outcome. A similar case can be found here and :

var content = new StringContent(postData, Encoding.UTF8, "application/json");
httpClient.PostAsync(uri, content);
Sign up to request clarification or add additional context in comments.

3 Comments

Please confirm @Vlad Efanov if the given solution worked.
@Vlad Efanov - Can you please post if the problem was resolved and how did you fix it?
@Vald Efanov- Were you able to resolve the issue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.