Should you use ChatGPT to jumpstart developing on Box Platform?
Box recently launched a brand new Box Developer Community for developers to directly engage with each other and with the developer relations team. But sometimes, you need an answer more quickly than just posting a question on a forum — enter ChatGPT!
In today’s blog post, let’s explore how the service can be an effective tool to aid developers in the process of creating solutions with Box Platform. I’ll showcase how ChatGPT can be used as a virtual assistant to provide guidance, answer questions, and generate code snippets related to the Box API.
I will also showcase some responses where ChatGPT is verging on incorrect information or just flat out wrong. As with all AI solutions, it is not perfect. Any and all information should be considered with a grain of salt. It also requires good prompting, as I show below!
That said, by integrating ChatGPT into your development workflow, you can enhance your productivity and get valuable insights to effectively leverage Box Platform in your applications.
If you want to follow along, make sure to create an account over on the ChatGPT website. In this tutorial, I show using the free option, but you are welcome to get the premium version if you wish.
You will also want to have a Box Enterprise account, and I recommend using a sandbox environment for testing out any and all development. You can find instructions on setting one up here.
OR you could ask ChatGPT. ;)
Once you have that — travel to the developer console and follow along.
…but first, it is quokka time.
Getting Started with Box Platform
To start, in ChatGPT, I simply wrote — “I’m a new user on Box. Write me step by step instructions on setting up an application in the developer console.” This was the response:
Sure! Here are step-by-step instructions on how to set up an application in the Box Developer Console:
Step 1: **Sign up for a Box Developer Account**
If you don't already have a Box Developer Account, go to https://developer.box.com/ and sign up for a free account.
Step 2: **Create a New App**
After signing in, navigate to the Box Developer Console at https://app.box.com/developers/console.
Step 3: **Create a New Custom App**
Click on the "Create New App" button in the top right corner.
Step 4: **Choose the App Type**
Select the type of app you want to create. For most scenarios, you'll likely choose "Custom App."
Step 5: **Choose Authentication Method**
Select the authentication method you want to use. The most common choice is "OAuth 2.0 with JWT (Server Authentication)" for server-to-server communication or "OAuth 2.0 with User Authentication" for user-facing applications.
Step 6: **Enter Basic App Information**
Fill out the basic information for your app:
- **App Name**: Provide a name for your application.
- **App Description**: Add a short description of your app's purpose.
- **App Logo**: Upload an image that represents your app (optional).
Step 7: **Configure App Access**
Specify the type of access your app requires:
- **Enterprise Access**: Allows your app to access all content owned by the enterprise.
- **App Users Access**: Restricts your app to access only content owned by the app users.
- **Standard Access**: Accesses only the content the user explicitly grants access to.
Step 8: **Add Scopes**
Select the API scopes your app requires. Scopes determine the level of access your app has to a user's Box account. For example, you can choose read-only access or full read-write access.
Step 9: **Configure User Authentication (if applicable)**
If you selected "OAuth 2.0 with User Authentication," you'll need to configure the user authentication settings, including the redirect URI and app URLs.
Step 10: **Generate RSA Key Pair (if applicable)**
If you selected "OAuth 2.0 with JWT (Server Authentication)," you'll need to generate an RSA key pair. This key pair is used to sign your JWT token for authentication.
Step 11: **Save Your Configuration**
Click the "Create App" button to save your app configuration.
Step 12: **Retrieve Your App Credentials**
After creating the app, you'll be provided with the necessary credentials, including the **Client ID** and, if applicable, the **Client Secret**. Store these credentials securely as they will be used in your application's authentication process.
Congratulations! You've successfully set up your application in the Box Developer Console. Now you can use the provided credentials to authenticate your app and start making API requests to Box on behalf of your users.
Remember to refer to the official Box API documentation (https://developer.box.com/reference) for detailed information on how to use the API and interact with Box services in your application. Happy coding! If you have any questions or need further assistance, feel free to ask.
Wow! That’s pretty cool. Lots of information and most of it is correct. Let’s analyze the response.
What did it get right?
The steps provided are done so in the right order. It covers all the major topics of app creation in Box, and it links to the correct URL for the developer site.
What did it get wrong?
Step one mentions creating a developer account. Because ChatGPT is based on information available to it pre-late 2021, it doesn’t know that currently we are revamping our free developer accounts. Right now — that type of account is not available. So, you either need to use an enterprise account to develop, or a free account that is restricted to OAuth 2.0 apps.
It also doesn’t mention that JWT apps need to be Authorized or that OAuth 2.0 may need to enabled by an administrator in order to actually make API calls.
What could be better?
It doesn’t go into a ton of detail on the scopes, app type choice, etc. This is probably because I wasn’t specific enough in my prompt. If I had asked it to be more specific — like by providing a use case, other infrastructure requirements, etc — it probably would’ve made the steps more informative.
Overall, if I was a new user(familiar with developing on APIs by SaaS companies) and I asked the above prompt, I would know generally what to do. But, if I didn’t confirm the information in the developer documentation, I might get stuck. Due to that, I would not rely on ChatGpt word for word on this topic.
Authentication
If I could pick one topic I see asked about most often, it would be authentication. Developing on Box does have a learning curve due to learning about our application, authentication, and user types. Depending on the use case, a different mix of those work best. So, it can be easy to get confused or bogged down, but let’s see if ChatGpt is up for the challenge to help!
I’m going to compare two prompt responses for this section to show how crafting more specific prompts greatly enhances the reply.
Prompt 1
“Explain the different authentication methods for Box Platform.”
Box Platform supports various authentication methods to allow developers to securely access the Box API on behalf of users or applications. Here are the main authentication methods supported by Box:
1. **OAuth 2.0 with User Authentication**:
This method is commonly used for user-facing applications, where the user needs to grant explicit permission for the application to access their Box account. The OAuth 2.0 flow involves the following steps:
- The application redirects the user to Box's login page.
- The user logs in to their Box account (if not already logged in) and is asked to authorize the application.
- Once the user grants permission, Box redirects the user back to the application with an authorization code.
- The application exchanges the authorization code for an access token, which it can use to make API requests on behalf of the user.
Advantages: User-specific access, no need to store user credentials, fine-grained control over permissions.
2. **OAuth 2.0 with JWT (Server Authentication)**:
This method is suitable for server-to-server communication or when you need to authenticate your application without user interaction. It uses JSON Web Tokens (JWT) to authenticate the application.
- The application generates an RSA key pair and registers the public key with Box during app creation.
- The application creates a JWT token with its client ID, timestamp, and other relevant information and signs it with the private key.
- The application exchanges the JWT token for an access token, which it can use to make API requests on behalf of the app.
Advantages: App-specific access, no user interaction required, suitable for background tasks and automation.
3. **Server Token Authentication**:
This method allows a server-side application to authenticate without the need for user credentials. The application authenticates itself using a unique "app token" generated by Box.
- The application includes the app token in the HTTP Authorization header of API requests.
- The app token is typically passed as a Bearer token in the following format: `Authorization: Bearer YOUR_APP_TOKEN`.
Advantages: App-specific access, no user interaction required, suitable for backend processes.
4. **JWT App Auth (As-User)**:
This method is an extension of the JWT server authentication flow and allows an application to authenticate as a user rather than as the application itself. It is useful for scenarios where an application needs to act on behalf of a user without the user's explicit authorization.
- The application requests a user-level access token by including the user's ID in the token request.
- The application can then use the user-level access token to make API requests as if it were the user.
Advantages: App acts as a specific user, useful for service accounts and automating tasks on behalf of users.
Remember to choose the appropriate authentication method based on your application's requirements and security considerations. Always handle authentication credentials securely and follow best practices to protect user data. For detailed implementation guidelines, refer to the official Box API documentation (https://developer.box.com/docs/authentication).
Prompt 2
“Create a script in Node. Use the Box Node SDK. I want to use Box Platform to manage Users who need created or deprovisioned. Explain authentication method selected and why. Explain in terms any one can understand. Write responses as comments in the script”
//Sure! Below is a Node.js script using the Box Node SDK to manage Box Platform users by creating or deprovisioning them. I'll add comments in the code to explain each step, including the authentication method selected:
// Required dependencies
const BoxSDK = require('box-node-sdk');
// Box API credentials
const clientID = 'YOUR_CLIENT_ID';
const clientSecret = 'YOUR_CLIENT_SECRET';
const appUserID = 'YOUR_APP_USER_ID';
const privateKeyPath = 'path/to/your/private_key.pem';
const privateKeyPassword = 'YOUR_PRIVATE_KEY_PASSWORD'; // If your private key has a password
// Create a new Box SDK instance
const sdk = new BoxSDK({
clientID,
clientSecret,
appAuth: {
keyID: appUserID,
privateKey: privateKeyPath,
passphrase: privateKeyPassword,
},
});
// Function to create a new Box user
async function createUser(name, login) {
try {
// Get an app user client, which will be used to make API requests on behalf of the app
const appUserClient = sdk.getAppAuthClient('user', appUserID);
// Create the user using the app user client
const user = await appUserClient.enterprise.addAppUser(name, { login });
console.log('User created successfully:', user);
} catch (error) {
console.error('Error creating user:', error.message);
throw error;
}
}
// Function to deprovision a Box user
async function deprovisionUser(userID) {
try {
// Get an app user client, which will be used to make API requests on behalf of the app
const appUserClient = sdk.getAppAuthClient('user', appUserID);
// Deprovision the user using the app user client
await appUserClient.enterprise.deprovisionUser(userID);
console.log('User deprovisioned successfully.');
} catch (error) {
console.error('Error deprovisioning user:', error.message);
throw error;
}
}
// Example usage of the functions
createUser('John Doe', 'john.doe@example.com')
.then(() => deprovisionUser('USER_ID_TO_DEPROVISION'))
.catch((error) => console.error('Error:', error.message));
// Explanation of the selected authentication method ("OAuth 2.0 with JWT (Server Authentication)"):
// - We are using the Box Node SDK, which internally handles the authentication process for us.
// - In the script, we set up the Box SDK by providing the client ID, client secret, and the necessary app authentication details, including the app user ID and the path to the private key.
// - With the SDK configured, it handles the JWT (JSON Web Token) authentication behind the scenes. The private key is used to sign the requests, proving that the application (acting on behalf of the app user) is authorized to perform actions on the Box Platform.
// - The app user client obtained from the SDK is an authenticated client, allowing the script to create or deprovision users using the Box API.
//Remember to replace the placeholders like `YOUR_CLIENT_ID`, `YOUR_CLIENT_SECRET`, `YOUR_APP_USER_ID`, `path/to/your/private_key.pem`, and `YOUR_PRIVATE_KEY_PASSWORD` with your actual Box API credentials and the desired values for user creation and deprovisioning.
//With this script, you can manage Box users programmatically and securely without the need for direct user interaction.
Analysis
As I’m sure you can tell, the difference between the two responses is drastic. Simply giving it my use case allowed it to decide the authentication method for me. Better yet, it choose correctly!
Adding on top of that, it created a usable Node script. Like, you could actually run that (assuming you installed dependancies and had an app set up).
Similar to the earlier section, some of the wording is incorrect. Nowadays, we refer to the auth types like the screenshot below. I also wish it would’ve assumed certain things. For example, it should use the Box Node SDK without me asking, and I would have like to see it generate a README file for a user to add to the solution; however, both of those are fixable with better prompt specificity.
Bonus
As an addendum to the above, I asked the service to retry discussing JWT in easy to understand verbiage. I love the “magic key” analogy it came up with. Check it out below.
For your Node.js script to manage Box Platform users, the most suitable authentication method would be "OAuth 2.0 with JWT (Server Authentication)." This method allows your script to authenticate itself securely and perform user management tasks without the need for direct user interaction.
Here's a simple explanation of why this authentication method is a good choice:
Imagine you have a magic key that allows you to perform tasks on behalf of your friends, even when they are not around. This magic key can do various things, like creating things or removing things for them.
In this scenario:
- You are the "script" or "application" that wants to manage Box users (your friends).
- Box Platform is like a big safe with all the user accounts.
- The "magic key" is the "OAuth 2.0 with JWT (Server Authentication)" method.
With "OAuth 2.0 with JWT (Server Authentication)":
1. You generate a special "magic key" (RSA key pair) that only you know (your application's private key).
2. You share the "public" part of the "magic key" (your application's public key) with Box Platform, so they recognize you as a trusted friend.
3. Whenever you want to create a new user or deprovision an existing user, you use your "magic key" (private key) to show Box Platform that you are authorized to perform these actions.
4. Box Platform trusts your "magic key" (because it matches the "public" part they have on file) and allows your script to create or deprovision users on behalf of your application.
The key advantage of this method is that it allows your script (application) to act as a reliable and trusted friend of Box Platform. It can carry out user management tasks without needing to ask users for their passwords or involve them directly, just like you can perform tasks for your friends without them being physically present.
Additionally, this authentication method is suitable for server-to-server communication and automation, which aligns well with your Node.js script's requirements for managing users programmatically.
Remember to keep your "magic key" (RSA private key) safe and secure, as it acts as the application's authentication token to Box Platform. Never share your private key or hardcode it in your script, as it should be treated like a secret.
In conclusion, "OAuth 2.0 with JWT (Server Authentication)" is the right authentication method for your Node.js script to securely manage Box users without requiring direct user interaction, just like a magic key allows you to help your friends without them needing to be present.
Mental health breaks
Sometimes when developing, I find it helpful to think about something else — you know, give my mind a breather. So, I asked it, “I need a mental health break. Can you tell me some funny dad jokes?”
Of course! I'm here to help lighten the mood. Here are some dad jokes for you:
1. Why don't scientists trust atoms? Because they make up everything!
2. How do you organize a space party? You planet!
3. What do you call fake spaghetti? An impasta!
4. Why don't some couples go to the gym? Because some relationships don't work out!
5. How do you catch a squirrel? Climb a tree and act like a nut!
6. What do you call a fish wearing a crown? King of the sea!
7. Why don't skeletons fight each other? They don't have the guts!
8. What did the grape do when it got stepped on? It let out a little wine!
9. Why did the scarecrow win an award? Because he was outstanding in his field!
10. How does a penguin build its house? Igloos it together!
I hope these dad jokes brought a smile to your face! Remember, taking a mental health break is essential, and laughter is a great way to relax and recharge. If you need more jokes or anything else, feel free to ask! Take care.
Since I love a glass of cab on a patio, I’m partial to number 8. I highly recommend when chatting to throw in some non topic related questions.
File uploads and downloads
Alright — back to Box! Since it is the leading cloud content management solution, I have to show sending prompts on file uploads and downloads.
Uploads
“Create a Node script using the Box Node SDK to upload a file from my local machine”
// Required dependencies
const BoxSDK = require('box-node-sdk');
const fs = require('fs');
// Box API credentials
const clientID = 'YOUR_CLIENT_ID';
const clientSecret = 'YOUR_CLIENT_SECRET';
const appToken = 'YOUR_APP_TOKEN'; // Only required for Server Token authentication
// Path to the file you want to upload
const filePath = 'path/to/your/file.txt';
// Box file destination folder ID
const destinationFolderID = 'FOLDER_ID_TO_UPLOAD_TO';
// Create a new Box SDK instance
const sdk = new BoxSDK({
clientID,
clientSecret,
});
// Function to upload a file to Box
async function uploadFile() {
try {
// Create a Box client with the appropriate authentication method (OAuth 2.0 with JWT or Server Token)
// Uncomment the desired authentication method based on your app setup
// OAuth 2.0 with JWT (Server Authentication)
const appAuthClient = sdk.getAppAuthClient('user', 'YOUR_APP_USER_ID');
// OR
// Server Token Authentication
// const appAuthClient = sdk.getAppAuthClient('enterprise', appToken);
// Read the file from your local machine
const fileStream = fs.createReadStream(filePath);
// Upload the file to Box
const uploadedFile = await appAuthClient.files.uploadFile(
destinationFolderID,
'file.txt', // Change this to the desired file name in Box
fileStream
);
console.log('File uploaded successfully:', uploadedFile);
} catch (error) {
console.error('Error uploading file:', error.message);
throw error;
}
}
// Call the uploadFile function
uploadFile().catch((error) => console.error('Error:', error.message));
Explanation:
- First, you'll need to install the Box Node SDK and the required dependencies (not shown in the script). You can do this using npm or yarn.
- Replace `YOUR_CLIENT_ID`, `YOUR_CLIENT_SECRET`, `YOUR_APP_TOKEN`, `path/to/your/file.txt`, and `FOLDER_ID_TO_UPLOAD_TO` with your actual Box API credentials, the path to the file you want to upload, and the ID of the destination folder in Box where you want to upload the file.
- The script defines a function called `uploadFile`, which handles the file upload process.
- It creates a Box client using the appropriate authentication method (either OAuth 2.0 with JWT or Server Token) based on your app's setup. Uncomment the desired authentication method and provide the appropriate user ID or app token as required.
- The script reads the file from your local machine using `fs.createReadStream`.
- The `appAuthClient.files.uploadFile` method is used to upload the file to the specified folder in Box. It takes the destination folder ID, the desired file name in Box, and the file stream as parameters.
Note: Depending on your app's authentication method, make sure to uncomment and set up the corresponding part of the authentication in the script. You should choose either OAuth 2.0 with JWT (Server Authentication) or Server Token Authentication based on your application's requirements and use one of them consistently throughout your app.
Downloads
“Create a Node script using the Box Node SDK to recursively download all files in a given folder ID”
// Required dependencies
const BoxSDK = require('box-node-sdk');
const fs = require('fs');
const path = require('path');
// Box API credentials
const clientID = 'YOUR_CLIENT_ID';
const clientSecret = 'YOUR_CLIENT_SECRET';
const appToken = 'YOUR_APP_TOKEN'; // Only required for Server Token authentication
// Box folder ID to download files from
const folderID = 'YOUR_FOLDER_ID_TO_DOWNLOAD_FROM';
// Local directory to save the downloaded files
const downloadDirectory = 'path/to/your/local/directory';
// Create a new Box SDK instance
const sdk = new BoxSDK({
clientID,
clientSecret,
});
// Function to download a single file from Box
async function downloadFile(fileID, filePath) {
try {
// Create a Box client with the appropriate authentication method (OAuth 2.0 with JWT or Server Token)
// Uncomment the desired authentication method based on your app setup
// OAuth 2.0 with JWT (Server Authentication)
const appAuthClient = sdk.getAppAuthClient('user', 'YOUR_APP_USER_ID');
// OR
// Server Token Authentication
// const appAuthClient = sdk.getAppAuthClient('enterprise', appToken);
// Download the file and save it to the specified local path
await appAuthClient.files.getReadStream(fileID, null).then((stream) => {
const destinationStream = fs.createWriteStream(filePath);
stream.pipe(destinationStream);
});
console.log('File downloaded successfully:', filePath);
} catch (error) {
console.error('Error downloading file:', error.message);
throw error;
}
}
// Function to recursively download all files in a folder and its subfolders
async function downloadFilesRecursively(folderID, localDirectory) {
try {
// Create a Box client with the appropriate authentication method (OAuth 2.0 with JWT or Server Token)
// Uncomment the desired authentication method based on your app setup
// OAuth 2.0 with JWT (Server Authentication)
const appAuthClient = sdk.getAppAuthClient('user', 'YOUR_APP_USER_ID');
// OR
// Server Token Authentication
// const appAuthClient = sdk.getAppAuthClient('enterprise', appToken);
// Get the folder details
const folder = await appAuthClient.folders.get(folderID, { fields: 'name,children' });
// Create a local directory for this folder
const currentLocalDirectory = path.join(localDirectory, folder.name);
if (!fs.existsSync(currentLocalDirectory)) {
fs.mkdirSync(currentLocalDirectory);
}
// Download all files in the folder
for (const item of folder.item_collection.entries) {
if (item.type === 'file') {
const filePath = path.join(currentLocalDirectory, item.name);
await downloadFile(item.id, filePath);
} else if (item.type === 'folder') {
// Recursively download files from subfolders
await downloadFilesRecursively(item.id, currentLocalDirectory);
}
}
} catch (error) {
console.error('Error downloading files recursively:', error.message);
throw error;
}
}
// Call the downloadFilesRecursively function
downloadFilesRecursively(folderID, downloadDirectory).catch((error) => console.error('Error:', error.message));
To recursively download all files in a given Box folder ID using the Box Node SDK, you can use the following Node.js script. The script will traverse the folder and its subfolders, downloading all files to a specified local directory.
Note: Please replace `YOUR_CLIENT_ID`, `YOUR_CLIENT_SECRET`, `YOUR_APP_TOKEN`, `YOUR_APP_USER_ID`, `YOUR_FOLDER_ID_TO_DOWNLOAD_FROM`, and `path/to/your/local/directory` with your actual Box API credentials, user or app token, the desired folder ID, and the local directory path where you want to save the downloaded files.
Also, make sure to choose either OAuth 2.0 with JWT (Server Authentication) or Server Token Authentication, and set up the corresponding part of the authentication in the script. Uncomment the desired authentication method based on your application's requirements and use one of them consistently throughout your app.
Analysis
In my opinion, this is where ChatGpt really shines. You give it parameters to follow (Node, Box, etc), a task to accomplish (upload file) and a deliverable (the script), and the service completes your prompt.
Now, does it get a 100% every time(anytime)? No. It does not replace code review, but it gives you a practically complete jumping off point.
Where this breaks down is once you go beyond a one goal script. Take the below prompt as an example.
“Create a Node based custom portal for Box. Use the Node SDK. Use multiple code files. Make sure to make a readme.”
Creating a complete custom portal for Box using the Node SDK and multiple code files requires significant development effort and would be beyond the scope of a single response. However, I can provide you with a high-level outline of the steps you can take to create such a custom portal along with a sample project structure and a basic README to get you started…
Now — I could try to do this with multiple prompts and a longer chat. Maybe I’ll do that in future blog post! ;)
Conclusion
As you can tell — chatting with an AI can not only be informative, it can also be fun! I hope this blog post demonstrates how ChatGPT can assist you with real-world questions and code snippets related to a Box API integration.
Also, I hope it shows that AI services are far from perfect. They have maturing to do, but the more specific you are in your prompts, the better responses you will get.
So — would I use ChatGPT to help jumpstart developing on Box Platform? Absolutely. In fact, I use it everyday, but I exercise caution with any results. And, that goes for anything I chat about, be it Box Platform or otherwise.
I try to remember to tell myself, if ask the right questions, I’m more likely to get complete and correct answers.
If you love the Box Platform content, make sure to subscribe to our blog! We release content every single week. Also, Feel free to reach out on the forum if you want to share some of your own experiences using ChatGPT to help with your Box Platform development.
Happy Coding!