Hi Everyone, I'm trying to upload image in media collection with the help of rest api in python, but its facing some 400 status code error,
Here is my my post method....
def save_image_to_cms(image_data):
cms_endpoint = "
http://localhost:3000/api/media"
image_data["_id"] = str(image_data["_id"])
response = requests.post(cms_endpoint, json=image_data)
if response.status_code == 200:
response_data = response.json()
print("Image saved in CMS:", response_data)
return response_data.get("id")
else:
print("Failed to save image in the CMS")
return None
...............
and here is the my image_data
image_data = {
"_id": ObjectId(),
"filename": filename,
"mimeType": image_file.mimetype,
"filesize": os.path.getsize(os.path.join(app.config['UPLOAD_FOLDER'], filename)),
"width": None,
"height": None,
"createdAt": datetime.now().isoformat(),
"updatedAt": datetime.now().isoformat(),
"url": image_url
}
anyone can be help me on that
No experience with Python, but I'll try and help. The image_data is all going to be created from Payload as the return data if the upload is successful.
In your requests.post you need to figure out how to send a multipart file stream, not just JSON. This SO might help:
https://stackoverflow.com/a/12385661Thanks @drojkind , I will check once
@dribbens I tried that way also it is not working, could you tell me which keys require for media image post operation
I think the handler looks for
files
in the request. What have you tried?
Sorry, no it is
file
not plural
Take a look at our test code for file uploads:
https://github.com/payloadcms/payload/blob/b682c76dc7e431f4bb8dd2887240956479ae74a4/test/uploads/int.spec.ts#L27
This is how we send http file uploads programatically. Of course this is with javascript and not Python, but the idea should be the same.
I just tried to hit the post api from the postman, But its showing 400 bad request
Im passing only fileName field
Oh and the test rest client is defined here:
https://github.com/payloadcms/payload/blob/b682c76dc7e431f4bb8dd2887240956479ae74a4/test/helpers/rest.ts#L146
Is there any error message with it?
Filename can be read off of the file, that shouldn't be needed.
Have you tried other files?
What does your request look like in postman?
just wait i share one screenshot, its easier to understand
please
please check once
Yeah, the
key
needs to be
file
Change
filename
to just
file
Yeah, Its working
Thank you so much @dribbens
Glad I could help!
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.