'Firebase Storage REST API
I need very simple static image server for my flutter app. I am thinking about Cloud Storage, because I don't want to worry about own server administrating. I am using experimental Flutter for Desktop as tool for preparation data for mobile app, so I can use only REST API. I found out that Firebase Storage doesn't have own REST API and uses Google Cloud's one. To upload image to Cloud Storage I should make something like this:
curl -X POST --data-binary @[IMAGE_LOCATION] \
-H "Authorization: Bearer [OAUTH2_TOKEN]" \
-H "Content-Type: image/jpeg" \
"https://www.googleapis.com/upload/storage/v1/b/[BUCKET_NAME]/o?uploadType=media&name=[IMAGE_NAME]"
The problem is I can't understand how to get [OAUTH2_TOKEN]
(access token) from my Dart code, and how to administrate my images (should I do something with Firebase Admin SDK?)
Could anyone help me, please?
Solution 1:[1]
I found answer to this question. First you need to create private key for service account in Firebase settings. Then use it to get access token using dart packages googleapis_auth
and http
.
var accountCredentials = ServiceAccountCredentials.fromJson({
"private_key_id": "<please fill in>",
"private_key": "<please fill in>",
"client_email": "<please fill in>@developer.gserviceaccount.com",
"client_id": "<please fill in>.apps.googleusercontent.com",
"type": "service_account"
});
var scopes = [
'https://www.googleapis.com/auth/cloud-platform',
];
var client = Client();
AccessCredentials credentials = await obtainAccessCredentialsViaServiceAccount(accountCredentials, scopes, client);
String accessToken = credentials.accessToken.data;
File image = File('path/to/image');
var request = Request(
'POST',
Uri.parse('https://storage.googleapis.com/upload/storage/v1/b/[BUCKET_NAME]/o?uploadType=media&name=images/$imageName'),
);
request.headers['Authorization'] = "Bearer $accessToken";
request.headers['Content-Type'] = "image/jpeg";
request.bodyBytes = await image.readAsBytes();
Response response = await Response.fromStream(await request.send());
print(response.statusCode);
client.close();
Get request you can make the similar way, but you have to encode firebase path to image:
var imagePath = 'images/img.jpg';
var encodedImagePath = Uri.encodeQueryComponent(imagePath);
var request = Request(
'GET',
Uri.parse('https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]/o/$encodedImagePath?alt=media'),
);
request.headers['Authorization'] = "Bearer $accessToken";
Google Cloud REST API: https://cloud.google.com/storage/docs/downloading-objects
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dabbel |