• Stars
    star
    407
  • Rank 102,356 (Top 3 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created about 9 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Box SDK for Python

โ€œbox-dev-logoโ€

Box Python SDK

image Documentation Status image image image image

Getting Started Docs: https://developer.box.com/guides/tooling/sdks/python/

Installing

pip install boxsdk

The current version of the SDK is v3.x --- With this release support for Python 3.5 and earlier (including 2.x) has been dropped. if you're looking for the code or documentation for v1.5.x, please see the 1.5 branch.

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': '[email protected]',
'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(f'The current user ID is {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(f'The current user ID is {user.id}')

Authorization

The Box API uses OAuth2 for auth. The SDK makes it relatively painless to work with OAuth2 tokens.

Server-to-Server Auth with JWT

The Python SDK supports your JWT Authentication applications.

Authenticating with a JWT requires some extra dependencies. To get them, simply

pip install "boxsdk[jwt]"

Instead of instantiating your Client with an instance of OAuth2, instead use an instance of JWTAuth.

from boxsdk import JWTAuth
from boxsdk import Client

auth = JWTAuth(
    client_id='YOUR_CLIENT_ID',
    client_secret='YOUR_CLIENT_SECRET',
    enterprise_id='YOUR_ENTERPRISE_ID',
    jwt_key_id='YOUR_JWT_KEY_ID',
    rsa_private_key_file_sys_path='CERT.PEM',
    rsa_private_key_passphrase='PASSPHRASE',
)

access_token = auth.authenticate_instance()
client = Client(auth)

This client is able to create application users:

ned_stark_user = client.create_user('Ned Stark')

These users can then be authenticated:

ned_auth = JWTAuth(
    client_id='YOUR_CLIENT_ID',
    client_secret='YOUR_CLIENT_SECRET',
    user=ned_stark_user,
    jwt_key_id='YOUR_JWT_KEY_ID',
    rsa_private_key_file_sys_path='CERT.PEM',
    rsa_private_key_passphrase='PASSPHRASE'
)
ned_auth.authenticate_user()
ned_client = Client(ned_auth)

Requests made with ned_client (or objects returned from ned_client's methods) will be performed on behalf of the newly created app user.

Traditional 3-legged OAuth2

Get the Authorization URL

from boxsdk import OAuth2

oauth = OAuth2(
    client_id='YOUR_CLIENT_ID',
    client_secret='YOUR_CLIENT_SECRET',
    store_tokens=your_store_tokens_callback_method,
)

auth_url, csrf_token = oauth.get_authorization_url('http://YOUR_REDIRECT_URL')

store_tokens is a callback used to store the access token and refresh token. You might want to define something like this:

def store_tokens(access_token, refresh_token):
    # store the tokens at secure storage (e.g. Keychain)

The SDK will keep the tokens in memory for the duration of the Python script run, so you don't always need to pass store_tokens.

Authenticate (Get Access/Refresh Tokens)

If you navigate the user to the auth_url, the user will eventually get redirected to http://YOUR_REDIRECT_URL?code=YOUR_AUTH_CODE. After getting the code, you will be able to use the code to exchange for an access token and refresh token.

The SDK handles all the work for you; all you need to do is run:

# Make sure that the csrf token you get from the `state` parameter
# in the final redirect URI is the same token you get from the
# get_authorization_url method.
assert 'THE_CSRF_TOKEN_YOU_GOT' == csrf_token
access_token, refresh_token = oauth.authenticate('YOUR_AUTH_CODE')

Create an Authenticated Client

from boxsdk import Client

client = Client(oauth)

And that's it! You can start using the client to do all kinds of cool stuff and the SDK will handle the token refresh for you automatically.

Instantiate a Client Given an Access and a Refresh Token

Alternatively, you can instantiate an OAuth2 object with the access token and refresh token. Once you have an oauth object you can pass that into the Client object to instantiate a client and begin making calls.

from boxsdk import Client, OAuth2

oauth = OAuth2(
    client_id='YOUR_CLIENT_ID',
    client_secret='YOUR_CLIENT_SECRET',
    access_token='ACCESS_TOKEN',
    refresh_token='REFRESH_TOKEN',
)

client = Client(oauth)
user = client.user().get()

This will retrieve the current user! From here you can use the client you created to start making calls.

Other Auth Options

For advanced uses of the SDK, three additional auth classes are provided:

  • CooperativelyManagedOAuth2: Allows multiple auth instances to share tokens.
  • RemoteOAuth2: Allows use of the SDK on clients without access to your application's client secret. Instead, you provide a retrieve_access_token callback. That callback should perform the token refresh, perhaps on your server that does have access to the client secret.
  • RedisManagedOAuth2: Stores access and refresh tokens in Redis. This allows multiple processes (possibly spanning multiple machines) to share access tokens while synchronizing token refresh. This could be useful for a multiprocess web server, for example.

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://developer.box.com/en/reference/get-metadata-templates-id/
# 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 body or query params, you can use **kwargs to pass extra params:

  • data - takes a jsonified dictionary of body parameters
  • params - takes a dictionary of query parameters
# https://developer.box.com/reference/post-folders/
# Creates a new folder

# JSONify the body
body = json.dumps({
        'name': 'test-subfolder',
        'parent': {
            'id': '0',
        }
})

client.make_request(
    'POST',
    client.get_url('folders'),
    params={'fields': 'name,id'},
    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>

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.

Versions

We use a modified version of Semantic Versioning for all changes. See version strategy for details which is effective from 30 July 2022.

Supported Version

Only the current MAJOR version of SDK is supported. New features, functionality, bug fixes, and security updates will only be added to the current MAJOR version.

A current release is on the leading edge of our SDK development, and is intended for customers who are in active development and want the latest and greatest features. Instead of stating a release date for a new feature, we set a fixed minor or patch release cadence of maximum 2-3 months (while we may release more often). At the same time, there is no schedule for major or breaking release. Instead, we will communicate one quarter in advance the upcoming breaking change to allow customers to plan for the upgrade. We always recommend that all users run the latest available minor release for whatever major version is in use. We highly recommend upgrading to the latest SDK major release at the earliest convenient time and before the EOL date.

Version schedule

Version Supported Environments State First Release EOL/Terminated
3 Python 3.6+ Supported 17 Jan 2022 TBD
2 EOL 01 Nov 2018 17 Jan 2022
1 EOL 10 Feb 2015 01 Nov 2018

Contributing

See CONTRIBUTING.md.

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 3.6, 3.7, 3.8, 3.9, 3.10 and PyPy (our CI is configured to run PyPy tests on pypy-3.6, pypy-3.7, pypy-3.8).

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.

More Repositories

1

spout

Read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way
PHP
4,194
star
2

t3js

DEPRECATED - A minimal component-based JavaScript framework
JavaScript
1,560
star
3

Anemometer

Box SQL Slow Query Monitor
JavaScript
1,369
star
4

kube-applier

kube-applier enables automated deployment and declarative configuration for your Kubernetes cluster.
Go
627
star
5

kube-iptables-tailer

A service for better network visibility for your Kubernetes clusters.
Go
538
star
6

box-ui-elements

React Components for Box's Design System and Pluggable Components
JavaScript
532
star
7

mojito

An automation platform that enables continuous localization.
Java
354
star
8

flaky

Plugin for nose or pytest that automatically reruns flaky tests.
Python
347
star
9

viewer.js

A viewer for documents converted with the Box View API
JavaScript
335
star
10

stalker

A jQuery plugin allowing elements to follow the user as they scroll a page.
JavaScript
227
star
11

boxcli

A command line interface for interacting with the Box API.
JavaScript
197
star
12

box-windows-sdk-v2

Windows SDK for v2 of the Box API. The SDK is built upon .NET Framework 4.5
C#
186
star
13

ClusterRunner

ClusterRunner makes it easy to parallelize test suites across your infrastructure in the fastest and most efficient way possible.
Python
180
star
14

box-node-sdk

A Javascript interface for interacting with the Box API. You can find the node package at
JavaScript
177
star
15

augmented_types

A PHP extension to enforce parameter and return type annotations
C++
166
star
16

bart

A collection of our critical PHP tools
PHP
163
star
17

box-java-sdk

The Box SDK for Java.
Java
153
star
18

memsniff

A tool for recording and displaying statistics on memcached traffic written in golang.
Go
143
star
19

genty

Genty, pronounced "gen-tee", stands for "generate tests". It promotes generative testing, where a single test can execute over a variety of input.
Python
119
star
20

box-ios-sdk

iOS SDK for the Box Content API
Swift
117
star
21

kube-exec-controller

An admission controller service and kubectl plugin to handle container drift in K8s clusters
Go
109
star
22

RainGauge

RainGauge
JavaScript
107
star
23

leche

DEPRECATED - Testing extensions for Mocha and Sinon
JavaScript
103
star
24

box-content-preview

JavaScript library for rendering files stored on Box
JavaScript
100
star
25

box-openapi

OpenAPI 3.0 Specification for the Box APIs
JavaScript
92
star
26

rotunicode

Python library for converting between a string of ASCII and Unicode chars maintaining readability
Python
77
star
27

brainy

A faster, safer templating library for PHP
PHP
66
star
28

mysqlutilities

Box's MySQL Utilities
Shell
65
star
29

samples

Code snippets and samples to demonstrate how to get the most out of the Box platform & API
JavaScript
64
star
30

box-android-sdk

Java
62
star
31

box-android-apptoapp-sdk

This SDK supports Box OneCloud integrations on Android that handle file โ€˜roundtripsโ€™. That is, it enables file open-edit-save scenarios between the Box app and partner apps without the need for partner apps to authenticate a Box user independently.
Java
57
star
32

box-salesforce-sdk

This is the Salesforce SDK for integrating with the Box Platform.
Apex
53
star
33

fast_assert

PHP
37
star
34

StatusWolf

Configurable operations dashboard designed to bring together the disparate datasources that operations teams need to manage and present them in a flexible and beautiful way.
PHP
36
star
35

shmock

SHorthand for MOCKing in PHPUnit
PHP
34
star
36

Makefile.test

A makefile used for running test executables
Python
32
star
37

error-reporting-with-kubernetes-events

A demonstration of how Box utilizes Kubernetes CustomResourceDefinitions and Events
Go
32
star
38

box-skills-kit-nodejs

Official toolkit library and boilerplate code for developing Box Skills.
JavaScript
27
star
39

shalam

DEPRECATED - A friendly tool for CSS spriting
JavaScript
25
star
40

developer.box.com

Box Developer Documentation - Content & Configuration
JavaScript
23
star
41

box-ios-browse-sdk

Objective-C
18
star
42

wavectl

Command Line Client For Wavefront
Python
18
star
43

box-ios-preview-sdk

Box iOS Preview SDK
Swift
17
star
44

clusterrunner-javascript-sdk

ClusterRunner JavaScript SDK that works in both node and browsers
HTML
16
star
45

box-ui-elements-demo

Demo react app for UI Elements
JavaScript
14
star
46

box-python-sdk-gen

Repository for generated Box Python SDK
Python
14
star
47

sdks

SDKs, CLI and other tools for using Box Platform
14
star
48

box-android-preview-sdk

Box Android Preview SDK
Java
13
star
49

box-android-browse-sdk

Java
12
star
50

hdrCompressor

Tool for saving HDR file as RGBM, RGBD, RGBE or LogLuv TGA file.
C
12
star
51

box-typescript-sdk-gen

Repository for generated Box TS SDK
TypeScript
11
star
52

box-annotations

JavaScript library for annotations on files rendered with Box Content Preview
TypeScript
11
star
53

etcdb

Etcd PEP 249 driver.
Python
10
star
54

box-content-preview-demo

Demo React App using the Preview UI Element
JavaScript
8
star
55

box-postman

The official Box Postman Collection
JavaScript
7
star
56

oauth2-php

A server implementation of OAuth 2.0 in PHP.
PHP
6
star
57

verold.github.io

Verold developer docs and tutorials
JavaScript
5
star
58

box-ios-share-sdk

Objective-C
4
star
59

box-windows-metadata-sdk-v2

Box Metadata C# SDK Plugin
C#
4
star
60

box-dotnet-sdk-gen

Repository for Box .NET autogenerated SDK
C#
4
star
61

uploaders

Write your own custom uploader to send 3D models/textures to Verold Studio.
4
star
62

homebrew-mojito

Homebrew tap for Box/mojito
Ruby
3
star
63

box-developer-changelog

Box Developer Changelog
JavaScript
3
star
64

box-java-sdk-samples

Sample apps for the Box Java SDK.
Java
2
star
65

box-languages

Languages used by other box projects
JavaScript
2
star
66

box-android-share-sdk

Java
2
star
67

puppet-clusterrunner

Installs ClusterRunner using Puppet
Puppet
2
star
68

cla

Landing page for CLA Agreements
1
star