How to create a Folder in the GCP Bucket using API

I want to create a Folder in the GCP Bucket using the API in a web application.

1 REPLY 1

Hi @Documently,

Welcome to Google Cloud Community!

To create a folder in a Google Cloud Storage bucket using the API, you will need to use the `POST` method and send a request to the `/b/{bucket}/o` endpoint. In the request, you will need to specify the bucket name in the URL path, set the `Content-Type` header to `application/json`, and include the `folder` property in the request body.
 
Here is an example of how to create a folder using the API in a web application:
 
import requests

# Set the API endpoint URL
api_endpoint = "https://www.googleapis.com/storage/v1/b/{bucket}/o"

# Set the bucket name
bucket_name = "my-bucket"

# Set the folder name
folder_name = "my-folder"

# Set the API key
api_key = "YOUR_API_KEY"

# Set the request headers
headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {api_key}"
}

# Set the request body
data = {
    "name": folder_name,
    "folder": True
}

# Send the POST request
response = requests.post(api_endpoint, headers=headers, json=data)

# Print the response status code
print(response.status_code)
This will create a folder with the name `my-folder` in the bucket `my-bucket`.
 
Keep in mind that you will need to have the correct permissions to create a folder in the bucket. You will also need to replace `YOUR_API_KEY` with your own API key, and `my-bucket` and `my-folder` with the appropriate names for your bucket and folder.
 
Note: Folders in the Google Cloud resource hierarchy are different from the folders concept covered in this page, which only applies to buckets and objects in Cloud Storage.
 
Thank you