Raw bytes as query parameter #7886
-
I'm using FastAPI to send pickled objects (using dill) to a remote server, but am having trouble sending/receiving my pickled object as raw bytes. I'm using a POST endpoint and requests for sending the data. The closest I've come to success is to specify the pickled object parameter as a query parameter of type bytes:
For example, using numpy's subtract function and pickling with dill, I get a byte string like:
My POST looks like this (using requests.post and f strings to post the byte string object for obj_oparam):
When I successfully receive this object at my endpoint, unpickling fails, because the byte string now looks like this:
The issue seems to be that FastAPI is assuming my obj_param is a string, and is therefore converting it to bytes, giving me a byte string of a byte string. I know that FastAPI treats raw bytes as strings "under the hood", so is this expected behaviour? Am I doing something wrong when sending my pickled object, or is there something else I should be doing on the receiving end? Hope that's clear. I'm new to APIs so would really appreciate any help you can give. Thanks for your patience and thanks for your help! |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
There's a few issues to be aware of here:
For what it's worth, if what you are trying to submit is something related to a numpy array, you might be better off using the |
Beta Was this translation helpful? Give feedback.
-
You should encode the raw bytes in base64 then send encoded data as any normal string parameter and decode it on server as base64 |
Beta Was this translation helpful? Give feedback.
-
Yes, @tincumagic's suggestion is also a great choice for this situation. The same warnings about pickling would still apply though! |
Beta Was this translation helpful? Give feedback.
-
Thanks for the detailed response @dmontagu ! |
Beta Was this translation helpful? Give feedback.
-
Thanks @dmontagu and @tincumagic ! Great explanation including the security risks @dmontagu 🙇♂️ 🍰 I think that solves your issue, right @doctorperceptron ? If so, you can close the issue. |
Beta Was this translation helpful? Give feedback.
There's a few issues to be aware of here:
Yes, this is expected behavior in the sense that you are actually sending
"b'\\x80\\x03cnumpy\\nsubtract\\nq\\x00.'"
to the server, so FastAPI will treat the received value as the result of converting that string into bytes, as you are seeing.If you want to receive the original bytes, you need to make the request to your server with the actual bytes in your query parameter (url-encoded), not the stringified version that you are currently sending. (I'm not 100% sure whether query parameters are allowed to have arbitrary (url-encoded) bytes, though.)
In general, you probably don't want to put arbitrary bytes in the query string; typically data …