Official Box Python SDK
Project description
Installing
pip install boxsdk
The current version of the SDK is v2.x — if you’re looking for the code or documentation for v1.5.x, please see the 1.5 branch. Note that all new features and fixes will be made on the 2.x branch; you should consider upgrading from 1.5.x at your earliest convenience. See the changelog for a list of breaking changes and added features between the major versions.
Getting Started
To get started with the SDK, get a Developer Token from the Configuration page of your app in the Box Developer Console. You can use this token to make test calls for your own Box account.
The SDK provides an interactive DevelopmentClient that makes it easy to test out the SDK in a REPL. This client will automatically prompt for a new Developer Token when it requires one, and will log HTTP requests and responses to aid in debugging and understanding how the SDK makes API calls.
>>> from boxsdk import DevelopmentClient
>>> client = DevelopmentClient()
Enter developer token: <ENTER DEVELOPER TOKEN HERE>
>>> user = client.user().get()
GET https://api.box.com/2.0/users/me {'headers': {'Authorization': '---wXyZ',
'User-Agent': 'box-python-sdk-2.0.0',
'X-Box-UA': 'agent=box-python-sdk/2.0.0; env=python/3.6.5'},
'params': None}
"GET https://api.box.com/2.0/users/me" 200 454
{'Date': 'Thu, 01 Nov 2018 23:32:11 GMT', 'Content-Type': 'application/json', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Strict-Transport-Security': 'max-age=31536000', 'Cache-Control': 'no-cache, no-store', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'BOX-REQUEST-ID': '0b50luc09ahp56m2jmkla8mgmh2', 'Age': '0'}
{'address': '',
'avatar_url': 'https://cloud.app.box.com/api/avatar/large/123456789',
'created_at': '2012-06-07T11:14:50-07:00',
'id': '123456789',
'job_title': '',
'language': 'en',
'login': 'user@example.com',
'max_upload_size': 16106127360,
'modified_at': '2018-10-30T17:01:27-07:00',
'name': 'Example User',
'phone': '',
'space_amount': 1000000000000000.0,
'space_used': 14330018065,
'status': 'active',
'timezone': 'America/Los_Angeles',
'type': 'user'}
>>> print('The current user ID is {0}'.format(user.id))
The current user ID is 123456789
Outside of a REPL, you can initialize a new Client with just the Developer Token to get started.
from boxsdk import OAuth2, Client
auth = OAuth2(
client_id='YOUR_CLIENT_ID',
client_secret='YOUR_CLIENT_SECRET',
access_token='YOUR_DEVELOPER_TOKEN',
)
client = Client(auth)
user = client.user().get()
print('The current user ID is {0}'.format(user.id))
Usage Documentation
Full documentation of the available functionality with example code is available in the SDK documentation pages, and there is also method-level documentation available on ReadTheDocs.
Making API Calls Manually
The Box API is continually evolving. As such, there are API endpoints available that are not specifically supported by the SDK. You can still use these endpoints by using the make_request method of the Client.
# https://box-content.readme.io/reference#get-metadata-schema
# Returns a Python dictionary containing the result of the API request
json_response = client.make_request(
'GET',
client.get_url('metadata_templates', 'enterprise', 'customer', 'schema'),
).json()
make_request() takes two parameters:
method -an HTTP verb like GET or POST
url - the URL of the requested API endpoint
The Client class and Box objects have a get_url method. Pass it an endpoint to get the correct URL for use with that object and endpoint.
For API calls which require a body, make_request() accepts **kwargs after method and url.
# https://developer.box.com/reference#update-terms-of-service-user-status
# Updates a user's ToS status
# JSONify the body
body = json.dumps({"is_accepted":true})
# Pass body as "data" argument
client.make_request(method, url, data = body)
Other Client Options
Logging Client
For more insight into the network calls the SDK is making, you can use the LoggingClient class. This class logs information about network requests and responses made to the Box API.
>>> from boxsdk import LoggingClient
>>> client = LoggingClient()
>>> client.user().get()
GET https://api.box.com/2.0/users/me {'headers': {u'Authorization': u'Bearer ---------------------------kBjp',
u'User-Agent': u'box-python-sdk-1.5.0'},
'params': None}
{"type":"user","id":"..","name":"Jeffrey Meadows","login":"..",..}
<boxsdk.object.user.User at 0x10615b8d0>
For more control over how the information is logged, use the LoggingNetwork class directly.
from boxsdk import Client
from boxsdk.network.logging_network import LoggingNetwork
# Use a custom logger
client = Client(oauth, network_layer=LoggingNetwork(logger))
Developer Token Client
The Box Developer Console allows for the creation of short-lived developer tokens. The SDK makes it easy to use these tokens. Use the get_new_token_callback parameter to control how the client will get new developer tokens as needed. The default is to prompt standard input for a token.
Development Client
For exploring the Box API, or to quickly get going using the SDK, the DevelopmentClient class combines the LoggingClient with the DeveloperTokenClient.
Customization
Custom Subclasses
Custom object subclasses can be defined:
from boxsdk import Client
from boxsdk import Folder
class MyFolderSubclass(Folder):
pass
client = Client(oauth)
client.translator.register('folder', MyFolderSubclass)
folder = client.folder('0')
>>> print folder
>>> <Box MyFolderSubclass - 0>
If an object subclass is registered in this way, instances of this subclass will be returned from all SDK methods that previously returned an instance of the parent. See BaseAPIJSONObjectMeta and Translator to see how the SDK performs dynamic lookups to determine return types.
Contributing
See CONTRIBUTING.rst.
Developer Setup
Create a virtual environment and install packages -
mkvirtualenv boxsdk
pip install -r requirements-dev.txt
Testing
Run all tests using -
tox
The tox tests include code style checks via pep8 and pylint.
The tox tests are configured to run on Python 2.7, 3.4, 3.5, 3.6, 3.7, and PyPy (our CI is configured to run PyPy tests on PyPy 4.0).
Questions, Bugs, and Feature Requests?
Need to contact us directly? Browse the issues tickets! Or, if that doesn’t work, file a new one and we will get back to you. If you have general questions about the Box API, you can post to the Box Developer Forum.
Copyright and License
Copyright 2019 Box, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for boxsdk-2.7.1-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | f9117c965d1cfa28dbcd1c286ebf1df1fe2a415f39733e7b0cb98b2a02ac0737 |
|
MD5 | 43d6bdce8398c627106abfc231a63579 |
|
BLAKE2b-256 | 4fae6dbd672c44726557fc4dda64034094dde8ccdde25055b7afa6f0f38f8204 |