Search code examples
pythonpython-requestsstrapi

How to send image to Strapi with Python Requests?


I'm trying to send image / files to Strapi collection type with Python Requests?

I have a collection type called log which has a single media (and two text fields). I don't know how to create a new log with an image.

I'm just mashing code, but this is what I have at the moment (I'm trying to make the image streamable hoping that would work):

import requests
from utils.networking import LOCAL, PORT

import io
import numpy as np
import matplotlib.pyplot as plt

# I converted the image from numpy array to png
buf = io.BytesIO()
plt.imsave(buf, cvimage, format='png')
image = buf.getvalue()

payload = {
    "Type": 'info'
    "Message": 'Testing',
}

req = requests.post(f'http://localhost:1337/logs', json=payload, data=image)

I've tried using requests.post's files parameter instead of data, but I couldn't get that working. Also, I've tried posting to /upload as well, but failed.


Solution

  • Finally did it...

    The main point is, you have to upload the images / files to /upload first. Then, to add the media to a collection type entry, in the media field, reference the id of what you just uploaded.

    Upload the media like this:

    import requests
    import json
    
    files = {'files': ('Screenshot_5.png', open('test.jpeg', 'rb'), 'image', {'uri': ''})}
    response = requests.post('http://localhost:1337/upload', files=files)
    
    print(response.status_code)
    # `response.text` holds the id of what you just uploaded
    

    Your media should be in the Strapi Media Library now (you should double-check this).

    Finally, now you can create a entry (as you normally would) and use the id of what you uploaded to add media.

    payload = {
        "Type": 'info',
        "Message": 'lorem ipsum beep bop',
        "Screenshot": 1, # this is the id of the media you uploaded
    }
    response = requests.post('http://localhost:1337/logs', json=payload)
    
    print(response.status_code)