httppostrequestjuliapushover

Julia HTTP POST request with image attachment


I'm struggling implementing a POST request with image attachment with the Julia HTTP package. In Python I can do (source from Pushover):

import requests
r = requests.post("https://api.pushover.net/1/messages.json", data = {
  "token": "APP_TOKEN",
  "user": "USER_KEY"
},
files = {
  "attachment": ("image.jpg", open("myimage.jpg", "rb"), "image/jpeg")
})

How can I do such a file attachment in simple ways with Julia/HTTP or another Julia package?

Many thanks!


Solution

  • This should be the equivalent request using HTTP.jl:

    import HTTP
    url = "http://localhost:8080" # check request with e.g. netcat -lp 8080
    open("cat.jpg") do io
        headers = []
        data = [
            "token" => "APP_TOKEN",
            "user" => "USER_KEY",
            "attachment" => io,
        ]
        body = HTTP.Form(data)
        HTTP.post(url, headers, body)
    end
    

    The filename (cat.jpg) and content type (image/jpeg) is inferred from the io.


    If you need better control, for example if you want the filename in the request to differ from the filename on disk, or if you want to manually specify Content-Type, you can manually construct a HTTP.Multipart entry, like this:

    data = [
        "token" => "APP_TOKEN",
        "user" => "USER_KEY",
        "attachment" => HTTP.Multipart("other_filename.jpg", io, "image/png"),
    ]
    

    You can compare/verify the request from HTTP.jl with the one from requests by using something like

    $ netcat -lp 8080
    

    and send the requests to http://localhost:8080.