-1

I have created an API test using the Python library Requests. I have a problem when i try to create a new product. The product payload contains an image. See the Postman POST request:-

enter image description here

I am trying to send an image as part of a JSON payload. See my code below:-

import requests
import json
import base64
from Utilities.resources import *
from Utilities.payloads import *
from Utilities.configurations import *

config = getConfig()

login_user_url = config['API']['productionUrl'] + ApiResources.userLogin
create_product_url = 'https://eshop-backend-101.herokuapp.com/api/v1/products'

print(create_product_url)

### Create a new product ###

## First get a user token - Login and get token
login_response = requests.post(login_user_url, json=userPayload(), headers=headerPayload())
get_login_json_response = login_response.json()
token = get_login_json_response['token']

## Use token to create product
print("CREATE A PRODUCT")

## https://stackoverflow.com/questions/29104107/upload-image-using-post-form-data-in-python-requests
image_file = "D:\\My Training Courses\\Python APUI Testing - Requests\\images\\testImage.jpg"

with open(image_file, "rb") as f:
    im_bytes = f.read()
im_b64 = base64.b64encode(im_bytes).decode("utf8")

headerWithBearerTokenWithFormDataPayload = {
                'Content-Type': 'multipart/form-data; boundary=<calculated when request is sent>',
                'Authorization': 'Bearer ' + token
        }

bodyPayload = {
                "name": "Product API Test",
                "description": "Product API Test description",
                "richDescription": "Product API Test rich description",
                "image": im_b64,
                "brand": "Product API Test brand",
                "price": 300,
                "category": "5f15d54cf3a046427a1c26e3",
                "countInStock": 10,
                "rating": 4,
                "numReviews": 22,
                "isFeatured": True
        }

## create_product_response = requests.post(create_product_url, json=newProductPayload(im_b64), headers=headerWithBearerTokenPayload(token))
create_product_response = requests.post(create_product_url, json=bodyPayload, headers=headerWithBearerTokenWithFormDataPayload)
print(create_product_response)

I am getting the following error:-

Traceback (most recent call last): File "D:\My Training Courses\Python APUI Testing - Requests\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen httplib_response = self._make_request( File "D:\My Training Courses\Python APUI Testing - Requests\lib\site-packages\urllib3\connectionpool.py", line 398, in _make_request conn.request(method, url, **httplib_request_kw) File "D:\My Training Courses\Python APUI Testing - Requests\lib\site-packages\urllib3\connection.py", line 239, in request super(HTTPConnection, self).request(method, url, body=body, headers=headers) File "C:\Python39\lib\http\client.py", line 1253, in request self._send_request(method, url, body, headers, encode_chunked) File "C:\Python39\lib\http\client.py", line 1299, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "C:\Python39\lib\http\client.py", line 1248, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "C:\Python39\lib\http\client.py", line 1047, in _send_output self.send(chunk) File "C:\Python39\lib\http\client.py", line 969, in send self.sock.sendall(data) File "C:\Python39\lib\ssl.py", line 1204, in sendall v = self.send(byte_view[count:]) File "C:\Python39\lib\ssl.py", line 1173, in send return self._sslobj.write(data) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "D:\My Training Courses\Python APUI Testing - Requests\lib\site-packages\requests\adapters.py", line 440, in send resp = conn.urlopen( File "D:\My Training Courses\Python APUI Testing - Requests\lib\site-packages\urllib3\connectionpool.py", line 785, in urlopen retries = retries.increment( File "D:\My Training Courses\Python APUI Testing - Requests\lib\site-packages\urllib3\util\retry.py", line 550, in increment raise six.reraise(type(error), error, _stacktrace) File "D:\My Training Courses\Python APUI Testing - Requests\lib\site-packages\urllib3\packages\six.py", line 769, in reraise raise value.with_traceback(tb) File "D:\My Training Courses\Python APUI Testing - Requests\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen httplib_response = self._make_request( File "D:\My Training Courses\Python APUI Testing - Requests\lib\site-packages\urllib3\connectionpool.py", line 398, in _make_request conn.request(method, url, **httplib_request_kw) File "D:\My Training Courses\Python APUI Testing - Requests\lib\site-packages\urllib3\connection.py", line 239, in request super(HTTPConnection, self).request(method, url, body=body, headers=headers) File "C:\Python39\lib\http\client.py", line 1253, in request self._send_request(method, url, body, headers, encode_chunked) File "C:\Python39\lib\http\client.py", line 1299, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "C:\Python39\lib\http\client.py", line 1248, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "C:\Python39\lib\http\client.py", line 1047, in _send_output self.send(chunk) File "C:\Python39\lib\http\client.py", line 969, in send self.sock.sendall(data) File "C:\Python39\lib\ssl.py", line 1204, in sendall v = self.send(byte_view[count:]) File "C:\Python39\lib\ssl.py", line 1173, in send return self._sslobj.write(data) urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "D:\My Training Courses\Python APUI Testing - Requests\Automation101EShopAPITests\TEST.py", line 55, in create_product_response = requests.post(create_product_url, json=bodyPayload, headers=headerWithBearerTokenWithFormDataPayload)
File "D:\My Training Courses\Python APUI Testing - Requests\lib\site-packages\requests\api.py", line 117, in post return request('post', url, data=data, json=json, **kwargs) File "D:\My Training Courses\Python APUI Testing - Requests\lib\site-packages\requests\api.py", line 61, in request return session.request(method=method, url=url, **kwargs) File "D:\My Training Courses\Python APUI Testing - Requests\lib\site-packages\requests\sessions.py", line 529, in request resp = self.send(prep, **send_kwargs) File "D:\My Training Courses\Python APUI Testing - Requests\lib\site-packages\requests\sessions.py", line 645, in send r = adapter.send(request, **kwargs) File "D:\My Training Courses\Python APUI Testing - Requests\lib\site-packages\requests\adapters.py", line 501, in send raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

ED209
  • 588
  • 1
  • 9
  • 26
  • Your payload should contain the data of the image file, or in whatever format that API is expecting it [could be base64 string]. But your exception is related to failed to make secure connection to the api url. First you should try to call any simple API and establish that you are able to make API calls to that url. – Anand Sowmithiran Jan 23 '22 at 16:47
  • did you try some kind of encoding? like base64 as mentioned above – rikyeah Jan 23 '22 at 16:47
  • I tried using 64 encoding. I have added my code to the bottom of the description above. – ED209 Jan 23 '22 at 17:03
  • I have rewritten the description section of the problem I am having – ED209 Jan 23 '22 at 17:25

1 Answers1

0

According to the documentation of requests you need to pass a dictionary as a json parameter, not a string. Same with headers parameter. So remove json.dumps from

bodyPayload = json.dumps(
        {
                "name": "Product API Test",
                "description": "Product API Test description",
                "richDescription": "Product API Test rich description",
                "image": im_b64,
                "brand": "Product API Test brand",
                "price": 300,
                "category": "5f15d54cf3a046427a1c26e3",
                "countInStock": 10,
                "rating": 4,
                "numReviews": 22,
                "isFeatured": True
        }
)
Bes Dollma
  • 383
  • 3
  • 10
  • I removed the 'json.dumps(' sections. But I am now getting a new error. See above updated issue section. – ED209 Jan 23 '22 at 20:26