Uploading files to Firebase Storage using REST API
Asked Answered
A

3

29

Right now, the Firebase documentation guides you on uploading files to Firebase Storage by using their JavaScript library.

I am operating a server without NodeJS installed. Is it possible to upload files like image, audio, through the Firebase REST API?

At the moment I am using curl in a bash script to send JSON. I would prefer not to store base64 encoding in a database field, I want the file to be stored in a folder inside the Storage section.

Storage folder shown below:

Storage Folder

Alnico answered 4/6, 2016 at 14:5 Comment(6)
You don't need a nodejs server, firebase storage is client side, you just need an html file with the firebase library included and with a javascript script.....Richrichara
@Richrichara it is being run on a server with no browser. You can't run a HTML page, sorry.Alnico
Ok ok i understand now...right now only the realtime database can be accessed using REST API... so i don't think you can upload a file that way without a nodes serverRichrichara
Understood. Do you know if the JavaScript library is using WebSockets for streaming data?Alnico
sorry i don't knowRichrichara
For the realtime database, the javascript library does in fact use websockets to stream dataDesireah
D
17

Firebase Storage uses Google Cloud Storage under the hood, so you can use the GCS REST API to get 90% of the way there. (Docs here.)

There's a couple differences.

  1. Download URLs won't be automatically generated until you access it through the Firebase Storage SDK.
  2. You won't be able to use Firebase Authentication to upload through the GCS REST endpoint. You'll either need to set up OAuth (which, you might be able to get through Google Sign in with Authentication) or a service account. (Here's an example of how you can authenticate from Node.js to GCS.)
Desireah answered 8/6, 2016 at 2:21 Comment(0)
H
16

It is possible to upload a document to Firebase storage using the REST API. I have implemented in Python with the requests library to set HTTP headers and make a POST request. The process should be similar in other languages or with cURL.

To upload without auth:

def firebase_upload():
"""
Executes a POST request to upload an image to Firebase Storage.
DEMONSTRATION ONLY, USE NO FURTHER!
args: None
returns: response (json) with the response to the request
usage: res = firebase_upload()
"""
    response = None

    file2upload = "/Your/Path/To/your_pic.png"
    file_binary = open(file2upload, "rb").read()

    # HTTP
    url2file = 'https://firebasestorage.googleapis.com/v0/b/<your-project-ID.appspot.com>/o/stash%2Fyour_pic.png'
    headers = {"Content-Type": "image/png"}

    r = requests.post(url2file, data=file_binary, headers=headers)
    response = r.json()

    return response

This uploads the image to a folder named 'stash'. Be sure to use %2F instead of forward-slash in the URL. Also, you will need to make your storage bucket public using Firebase Rules. A successful response will return JSON like the following:


    {'name': 'stash/your_pic.png',
    'bucket': '<your-project-ID>.appspot.com',
    'generation': '1608437408388390',
    'metageneration': '1',
    'contentType': 'image/png',
    'timeCreated': '2020-12-20T04:10:08.388Z',
    'updated': '2020-12-20T04:10:08.388Z',
    'storageClass': 'STANDARD',
    'size': '52628',
    'md5Hash': 'mmkqwEek6tMAZmvooQ9X7g==',
    'contentEncoding': 'identity',
    'contentDisposition': "inline; filename*=utf-8''your_pic.png",
    'crc32c': 'fhlSmw==',
    'etag': 'CKaq+6LY2+0CEAE=',
    'downloadTokens': '<secure_token>'}

To upload with auth, the procedure is the same except you pass an auth token (obtained using the REST end-point for auth) with the HTTP header. Modify one line of code in the function like so.

    headers = {"Content-Type": "image/png", "Authorization": "Bearer "+auth_token}

The download URL is the url2file with the addition of 'downloadTokens' from the API response. Add: '?alt=media&token=' followed by the token string.

The example shows how to add an image to Firebase storage and all CRUD operations can be performed with the REST API by tweaking this pattern.

Heikeheil answered 27/12, 2020 at 2:26 Comment(3)
This answer has useful info for obtaining an auth token: #49905950Juliannajulianne
If you are searching for a way to add metadata to your files with the rest api, see the following answer: https://mcmap.net/q/502416/-firebase-storage-api-upload-file-with-metadaJackfish
Have a way to delete a doc from storage using something like this?Claresta
H
0

I found Sun Bee's answer really helpful, just wanted to add some notes for adding metadata since that wasn't straightforward for me.

def firebase_upload():
"""
Executes a POST request to upload an image to Firebase Storage.
DEMONSTRATION ONLY, USE NO FURTHER!
args: None
returns: response (json) with the response to the request
usage: res = firebase_upload()
"""
    response = None

    file2upload = "/Your/Path/To/your_pic.png"
    bucket = '<your-project-ID.appspot.com>'
    storage_path = 'cloud/path/to/your/pic.png'.replace('/', '%2F')
    token = '<your-firebase-token>'

    # HTTP
    url2file = f'https://firebasestorage.googleapis.com/v0/b/{bucket}/o/{storage_path}'
    headers = {
                "Authorization": f"Firebase {token}",
                "X-Goog-Upload-Protocol": "multipart"
              }

    files = {                                                                                                                                                                                                                                                    
      'metadata': (None, '{"metadata":{"mykey":"myvalue"}}', 'application/json'),                                                                                                                                                                        
      'file': open(file2upload, 'rb'),                                                                                                                                                                                                             
            }                                                                                                                                                                                                                                          
    r = requests.post(url, files=files, headers=headers)

    response = r.json()

    return response
Haircut answered 1/9, 2023 at 17:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.