2

I'm trying to upload a file in an API that just says:

REQUEST The request body should contain the contents of the file. https://developer.fortnox.se/documentation/resources/inbox/

What I've tried so far:

headers = {
      "Access-Token": settings.FORTNOX_ACCESS_TOKEN,
      "Client-Secret": settings.FORTNOX_CLIENT_SECRET,
      "Content-Type": "multipart/form-data",
      "Accept": "application/json",
}

file = open(invoice.file.path, 'rb').read()
r = requests.post("https://api.fortnox.se/3/inbox", data=file, headers=headers)

This gives me an error:

Ingen fil var uppladdad. (No file was uploaded)

headers = {
      "Access-Token": settings.FORTNOX_ACCESS_TOKEN,
      "Client-Secret": settings.FORTNOX_CLIENT_SECRET,
      "Content-Type": "multipart/form-data",
      "Accept": "application/json",
}

h = httplib2.Http()
file = open(invoice.file.path, 'rb').read()
resp, content = h.request('https://api.fortnox.se/3/inbox', "POST", body=file, headers=headers)

This gives me the same error:

Ingen fil var uppladdad. (No file was uploaded)

Are there any other ways to add the file to the request body, or am I doing something wrong here?

Thanks for any help.

saturnusringar
  • 149
  • 3
  • 13

3 Answers3

1

I finally got it working, based on the answer by mee. This did the trick:

multipart_data = MultipartEncoder(
    fields={
        'file': (invoice.file.path, open(invoice.file.path, 'rb'), 'text/plain')
    }
)

headers = {
  "Access-Token": settings.FORTNOX_ACCESS_TOKEN,
  "Client-Secret": settings.FORTNOX_CLIENT_SECRET,
  "Content-Type": multipart_data.content_type,
  "Accept": "application/json",
}

r = requests.post("https://api.fortnox.se/3/inbox", headers=headers, data=multipart_data)
saturnusringar
  • 149
  • 3
  • 13
0

In my case, I was able to upload file from put request like this:

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
def upload_localfile(filepath,server_data):
  multipart_data = MultipartEncoder(
    fields={
            'file': (filepath, open(filepath, 'rb'), 'text/plain')
           }
    )
  response=requests.put(
    server_data, 
    data=multipart_data,
    headers={'Content-Type': multipart_data.content_type}
    )
mee
  • 688
  • 8
  • 18
  • Thanks for the reply. I tried this: `multipart_data = MultipartEncoder(fields={'file': (invoice.file.path, open(invoice.file.path, 'rb'), 'text/plain')})` `requests.post("https://api.fortnox.se/3/inbox", data=multipart_data, headers=headers)` but I'm still getting the No file was uploaded-error. – saturnusringar Jun 13 '19 at 11:25
0

You should use this implementation for fortnox:

    files = [
        ('file', ('somename.pdf', data.file -> NamedTemporaryFile in my case))
    ]
    response = requests.post(
        url,
        headers={"Authorization": f"Bearer {token}",}
        data={},
        files=files,
    )
Dharman
  • 30,962
  • 25
  • 85
  • 135
AndyK
  • 31
  • 1
  • 3