How can I download an audio mp3 file and save it?

My View:

class UserSearchView(APIView):

    def get(self, request, link):
        url = config('BASE_URL')
        querystring = {"track_url": f'{link}'}
        headers = {
            "X-RapidAPI-Key": config('API_KEY'),
            "X-RapidAPI-Host": config('API_HOST')
        }

        response = requests.request("GET", url, headers=headers, params=querystring)

        data = response.json()


        return JsonResponse(data)

My response :

{
    "url": "https://result.s3.amazonaws.com/2022-11-13/61566981.mp3"
}

Not sure how to proceed here, can anyone help ?----------------------

I am not sure 100% but you can probably look for python libraries that will ease up the process of handling .mp3 files https://www.youtube.com/watch?v=n2FKsPt83_A

You got this far, good.

        response = requests.request("GET", url, headers=headers, params=querystring)

Now, just save the mp3.

        with open("music.mp3", "wb") as fout:
            fout.write(response.content)

EDIT

Here's a demo.

#! /usr/bin/env python3
from pathlib import Path

import requests


def download(url, out_file="audio.mp3"):
    out_file = Path(f"~/Desktop/{out_file}").expanduser()
    resp = requests.get(url)
    resp.raise_for_status()
    with open(out_file, "wb") as fout:
        fout.write(resp.content)


if __name__ == "__main__":
    npr = "https://play.podtrac.com/npr-500005/edge1.pod.npr.org/anon.npr-mp3/npr"
    download(f"{npr}/newscasts/2022/11/13/20221113_newscasts_long_140735.mp3")
Back to Top