• This repository has been archived on 20/Jan/2020
  • Stars
    star
    511
  • Rank 83,085 (Top 2 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created over 9 years ago
  • Updated over 5 years ago

Reviews

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

Repository Details

DEPRECATED — Coinbase Python API

Coinbase

The official Python library for the Coinbase API V2.

Important: this library currently targets the API V2, and the OAuth client requires V2 permissions (i.e. wallet:accounts:read). If you're still using the API V1, please use the old version of this library.

Features

  • Near-100% test coverage.
  • Support for both API Key + Secret and OAuth 2 authentication.
  • Convenient methods for making calls to the API - packs JSON for you!
  • Automatic parsing of API responses into relevant Python objects.
  • All objects have tab-completable methods and attributes when using IPython.

Installation

coinbase is available on PYPI. Install with pip:

pip install coinbase

or with easy_install:

easy_install coinbase

The library is currently tested against Python versions 2.7 and 3.4+.

Note: this package name used to refer to the unofficial coinbase_python library maintained by George Sibble. George graciously allowed us to use the name for this package instead. You can still find that package on Github. Thanks, George.

Documentation

The first thing you'll need to do is sign up with Coinbase.

API Key + Secret

If you're writing code for your own Coinbase account, enable an API key.

Next, create a Client object for interacting with the API:

from coinbase.wallet.client import Client
client = Client(api_key, api_secret)

OAuth2

If you're writing code that will act on behalf of another user, start by creating a new OAuth 2 application from the API settings page. You will need to do some work to obtain OAuth credentials for your users; while outside the scope of this document, please refer to our OAuth 2 flow documentation. Once you have these credentials (an access_token and refresh_token), create a client:

from coinbase.wallet.client import OAuthClient
client = OAuthClient(access_token, refresh_token)

Making API Calls

Both the Client and OAuthClient support all of the same API calls. We've included some examples below, but in general the library has Python classes for each of the objects described in our REST API documentation. These classes each have methods for making the relevant API calls; for instance, coinbase.wallet.model.Order.refund maps to the "refund order" API endpoint. The docstring of each method in the code references the endpoint it implements.

Every method supports the passing of arbitrary parameters via keyword. These keyword arguments will be sent directly to the relevant endpoint. If a required parameter is not supplied, the relevant error will be raised.

Each API method returns an APIObject (a subclass of dict) representing the JSON response from the API, with some niceties like pretty-printing and attr-style item access (response.foo is equivalent to response['foo']). All of the models are dumpable with JSON:

user = client.get_current_user()
user_as_json_string = json.dumps(user)

And, when the response data is parsed into Python objects, the appropriate APIObject subclasses will be used automatically. See the code in coinbase.wallet.model for all of the relevant classes, or the examples below. API methods that return lists of objects (for instance, client.get_accounts() return APIObject instances with nice wrappers around the data of the response body. These objects support direct indexing and slicing of the list referenced by data.

accounts = client.get_accounts()
assert isinstance(accounts.data, list)
assert accounts[0] is accounts.data[0]
assert len(accounts[::]) == len(accounts.data)

But, the APIObject is not actually a list (it's a subclass of dict) so you cannot iterate through the items of data directly. Simple slicing and index access are provided to make common uses easier, but to access the actual list you must reference the data attribute.

Refreshing

All the objects returned by API methods are subclasses of the APIObject and support being "refreshed" from the server. This will update their attributes and all nested data by making a fresh GET request to the relevant API endpoint:

accounts = client.get_accounts()
# Create a new account via the web UI
accounts.refresh()
# Now, the new account is present in the list

Warnings

The API V2 will return relevant *warnings* along with the response data. In a successful API response, any warnings will be present as a list on the returned APIObject:

accounts = client.get_accounts()
assert (accounts.warnings is None) or isinstance(accounts.warnings, list)

All warning messages will also be alerted using the Python stdlib warnings module.

Pagination

Several of the API V2 endpoints are paginated. By default, only the first page of data is returned. All pagination data will be present under the pagination attribute of the returned APIObject:

accounts = client.get_accounts()
assert (accounts.pagination is None) or isinstance(accounts.pagination, dict)

Error Handling

All errors occuring during interaction with the API will be raised as exceptions. These exceptions will be subclasses of coinbase.wallet.error.CoinbaseError. When the error involves an API request and/or response, the error will be a subclass of coinbase.error.APIError, and include request and response attributes with more information about the failed interaction. For full details of error responses, please refer to the relevant API documentation.

Error HTTP Status Code
APIError
TwoFactorRequiredError 402
ParamRequiredError 400
ValidationError 422
InvalidRequestError 400
PersonalDetailsRequiredError 400
AuthenticationError 401
UnverifiedEmailError 401
InvalidTokenError 401
RevokedTokenError 401
ExpiredTokenError 401
InvalidScopeError 403
NotFoundError 404
RateLimitExceededError 429
InternalServerError 500
ServiceUnavailableError 503

OAuth Client

The OAuth client provides a few extra methods to refresh and revoke the access token.

# exchange the current access_token and refresh_token for a new pair
oauth_client.refresh()

This method will update the values stored in the client and return a dict containing information from the token endpoint so that you can update your records.

# revoke the current access_token and refresh_token
oauth_client.revoke()

Protip: You can test OAuth2 authentication easily with Developer Access Tokens which can be created in your OAuth2 application settings. These are short lived tokens which authenticate but don't require full OAuth2 handshake to obtain.

Two Factor Authentication

Sending money may require the user to supply a 2FA token in certain situations. If this is the case, a TwoFactorRequiredError will be raised:

from coinbase.wallet.client import Client
from coinbase.wallet.error import TwoFactorRequiredError

client = Client(api_key, api_secret)
account = client.get_primary_account()
try:
  tx = account.send_money(to='[email protected]', amount='1', currency='BTC')
except TwoFactorRequiredError:
  # Show 2FA dialog to user and collect 2FA token
  # two_factor_token = ...
  # Re-try call with the `two_factor_token` parameter
  tx = account.send_money(to='[email protected]', amount='1', currency='BTC', two_factor_token="123456")

Notifications/Callbacks

Verify notification authenticity

client.verify_callback(request.body, request.META['CB-SIGNATURE']) # true/false

Usage

This is not intended to provide complete documentation of the API. For more details, please refer to the official documentation. For more information on the included models and abstractions, please read the code – we've done our best to make it clean, commented, and understandable.

Market Data

Get supported native currencies

client.get_currencies()

Get exchange rates

client.get_exchange_rates()

Buy price

client.get_buy_price(currency_pair = 'BTC-USD')

Sell price

client.get_sell_price(currency_pair = 'BTC-USD')

Spot price

client.get_spot_price(currency_pair = 'BTC-USD')

Current server time

client.get_time()

Users

Get authorization info

client.get_auth_info()

Get user

client.get_user(user_id)

Get current user

client.get_current_user()

Update current user

client.update_current_user(name="New Name")
# or
current_user.modify(name="New Name")

Accounts

Get all accounts

client.get_accounts()

Get account

client.get_account(account_id)

Get primary account

client.get_primary_account()

Set account as primary

client.set_primary_account(account_id)
# or
account.set_primary()

Create a new bitcoin account

client.create_account()

Update an account

client.update_account(account_id, name="New Name")
# or
account.modify(name="New Name")

Delete an account

client.delete_account(account_id)
# or
account.delete()

Addresses

Get receive addresses for an account

client.get_addresses(account_id)
# or
account.get_addresses()

Get a receive address

client.get_address(account_id, address_id)
# or
account.get_address(address_id)

Get transactions for an address

client.get_address_transactions(account_id, address_id)
# or
account.get_address_transactions(address_id)

Create a new receive address

client.create_address(account_id)
# or
account.create_address(address_id)

Transactions

Get transactions

client.get_transactions(account_id)
# or
account.get_transactions()

Get a transaction

client.get_transaction(account_id, transaction_id)
# or
account.get_transaction(transaction_id)

Send money

client.send_money(
    account_id,
    to="3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy",
    amount="1",
    currency="BTC")
# or
account.send_money(to="3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy",
                   amount="1",
                   currency="BTC")

Transfer money

client.transfer_money(
    account_id,
    to="<coinbase_account_id>",
    amount="1",
    currency="BTC")
# or
account.transfer_money(to="<coinbase_account_id>",
                       amount="1",
                       currency="BTC")

Request money

client.request_money(
    account_id,
    to="<email_address>",
    amount="1",
    currency="BTC")
# or
account.request_money(to="<email_address>",
                      amount="1",
                      currency="BTC")

Resend request

client.resend_request(account_id, request_id)

Complete request

client.complete_request(account_id, request_id)

Cancel request

client.cancel_request(account_id, request_id)

Reports

Get all reports

client.get_reports()

Get report

client.get_report(report_id)

Create report

client.create_report(type='transactions', email='[email protected]')  # types can also be 'orders' or 'transfers'

Buys

Get buys

client.get_buys(account_id)
# or
account.get_buys()

Get a buy

client.get_buy(account_id, buy_id)
# or
account.get_buy(buy_id)

Buy bitcoins

client.buy(account_id, amount='1', currency='BTC')
# or
account.buy(amount='1', currency='BTC')

Commit a buy

You only need to do this if the initial buy was explicitly uncommitted.

buy = account.buy(amount='1', currency='BTC', commit=False)

client.commit_buy(account_id, buy.id)
# or
account.commit_buy(buy.id)
# or
buy.commit()

Sells

Get sells

client.get_sells(account_id)
# or
account.get_sells()

Get a sell

client.get_sell(account_id, sell_id)
# or
account.get_sell(sell_id)

Sell bitcoins

client.sell(account_id, amount='1', currency='BTC')
# or
account.sell(amount='1', currency='BTC')

Commit a sell

You only need to do this if the initial sell was explicitly uncommitted.

sell = account.sell(amount='1', currency='BTC', commit=False)

client.commit_sell(account_id, sell.id)
# or
account.commit_sell(sell.id)
# or
sell.commit()

Deposits

Get deposits

client.get_deposits(account_id)
# or
account.get_deposits()

Get a deposit

client.get_deposit(account_id, deposit_id)
# or
account.get_deposit(deposit_id)

Deposit money

client.deposit(account_id, amount='1', currency='USD')
# or
account.deposit(amount='1', currency='USD')

Commit a deposit

You only need to do this if the initial deposit was explicitly uncommitted.

deposit = account.deposit(amount='1', currency='USD', commit=False)

client.commit_deposit(account_id, deposit.id)
# or
account.commit_deposit(deposit.id)
# or
deposit.commit()

Withdrawals

Get withdrawals

client.get_withdrawals(account_id)
# or
account.get_withdrawals()

Get a withdrawal

client.get_withdrawal(account_id, withdrawal_id)
# or
account.get_withdrawal(withdrawal_id)

Withdraw money

client.withdraw(account_id, amount='1', currency='USD')
# or
account.withdraw(amount='1', currency='USD')

Commit a withdrawal

You only need to do this if the initial withdrawal was explicitly uncommitted.

withdrawal = account.withdrawal(amount='1', currency='USD', commit=False)

client.commit_withdrawal(account_id, withdrawal.id)
# or
account.commit_withdrawal(withdrawal.id)
# or
withdrawal.commit()

Payment Methods

Get payment methods

client.get_payment_methods()

Get a payment method

client.get_payment_method(payment_method_id)

Merchants

Get a merchant

client.get_merchant(merchant_id)

Orders

Get orders

client.get_orders()

Get a order

client.get_order(order_id)

Create an order

client.create_order(amount='1', currency='BTC', name='Order #1234')

Refund an order

client.refund_order(order_id)
# or
order = client.get_order(order_id)
order.refund()

Checkouts

Get checkouts

client.get_checkouts()

Get a checkout

client.get_checkout(checkout_id)

Create a checkout

client.create_checkout(amount='1', currency='BTC', name='Order #1234')

Get a checkout's orders

client.get_checkout_orders(checkout_id)
# or
checkout = client.get_checkout(checkout_id)
checkout.get_orders()

Create an order for a checkout

client.create_checkout_order(checkout_id)
# or
checkout = client.get_checkout(checkout_id)
checkout.create_order()

Testing / Contributing

Any and all contributions are welcome! The process is simple: fork this repo, make your changes, run the test suite, and submit a pull request. Tests are run via nosetest. To run the tests, clone the repository and then:

# Install the requirements
pip install -r requirements.txt
pip install -r test-requirements.txt

# Run the tests for your current version of Python
make tests

If you'd also like to generate an HTML coverage report (useful for figuring out which lines of code are actually being tested), make sure the requirements are installed and then run:

make coverage

We use tox to run the test suite against multiple versions of Python. You can install tox with pip or easy_install:

pip install tox
easy_install tox

Tox requires the appropriate Python interpreters to run the tests in different environments. We recommend using pyenv for this. Once you've installed the appropriate interpreters, running the tests in every environment is simple:

tox

More Repositories

1

terraform-landscape

Improve Terraform's plan output to be easier to read and understand
Ruby
1,546
star
2

coinbase-wallet-sdk

An open protocol that lets users connect their mobile wallets to your DApp
TypeScript
1,276
star
3

coinbase-pro-trading-toolkit

DEPRECATED — The Coinbase Pro trading toolkit
TypeScript
856
star
4

kryptology

Go
838
star
5

coinbase-pro-node

DEPRECATED — The official Node.js library for Coinbase Pro
JavaScript
828
star
6

build-onchain-apps

Accelerate your web3 creativity with the Build Onchain Apps Toolkit. ⛵️
TypeScript
570
star
7

odin

Archived: Odin deployer to AWS for 12 Factor applications.
Go
540
star
8

assume-role

DEPRECATED — assume-role: a CLI tool making it easy to assume IAM roles through an AWS Bastion account
Shell
424
star
9

geoengineer

DEPRECATED — Infrastructure As Code
Ruby
403
star
10

coinbase-node

DEPRECATED — The official Node.js library for the Coinbase API.
JavaScript
361
star
11

mesh-specifications

Specification files for the Rosetta Blockchain Standard
Shell
313
star
12

coinbase-php

DEPRECATED — PHP wrapper for the Coinbase API
PHP
293
star
13

onchainkit

React components and TypeScript utilities for top-tier onchain apps.
TypeScript
287
star
14

cbpay-js

Coinbase Pay SDK
TypeScript
270
star
15

coinbase-ruby

DEPRECATED — Ruby wrapper for the Coinbase API
Ruby
239
star
16

waas-sdk-react-native

Coinbase Wallet as a Service (WaaS) SDK for React Native. Enables MPC Operations for iOS and Android Devices.
TypeScript
222
star
17

step

step is a framework for building, testing and deploying AWS Step Functions and Lambda
Go
207
star
18

wallet-mobile-sdk

An open protocol for mobile web3 apps to interact with wallets
Kotlin
203
star
19

temporal-ruby

Ruby SDK for Temporal
Ruby
194
star
20

mesh-sdk-go

Rosetta Client Go SDK
Go
182
star
21

coinbase-ios-sdk

Integrate bitcoin into your iOS application with Coinbase
Swift
172
star
22

nft-dapp-starter-kit

Starter kit for developers who want to build an NFT minting site
TypeScript
153
star
23

coinbase-java

Coinbase API v1 library for Java
Java
146
star
24

coinbase-commerce-node

Coinbase Commerce Node
JavaScript
143
star
25

mesh-cli

CLI for the Rosetta API
Go
142
star
26

waas-client-library-go

Coinbase Wallet as a Service (WaaS) Client Library in Go.
Go
138
star
27

traffic_jam

DEPRECATED — Ruby library for time-based rate limiting
Ruby
129
star
28

coinbase-commerce-php

Coinbase Commerce PHP
PHP
127
star
29

coinbase-exchange-ruby

DEPRECATED — Official Ruby library for the GDAX API
Ruby
122
star
30

dexter

Forensics acquisition framework designed to be extensible and secure
Go
118
star
31

multisig-tool

DEPRECATED — Multisig Vault recovery tool
JavaScript
110
star
32

mesh-bitcoin

Bitcoin Rosetta API Implementation
Go
104
star
33

smart-wallet

Solidity
103
star
34

mesh-ethereum

Ethereum Rosetta API Implementation
Go
98
star
35

coinbase-android-sdk

DEPRECATED — Android SDK for Coinbase
Java
95
star
36

mongobetween

Go
93
star
37

fenrir

Archived: AWS SAM deployer to manage serverless projects.
Go
91
star
38

react-coinbase-commerce

Coinbase Commerce React
JavaScript
91
star
39

pwnbot

You call PwnBot in Slack on someone else's unlocked computer
JavaScript
89
star
40

digital-asset-policy-proposal

Digital Asset Policy Proposal: Safeguarding America’s Financial Leadership
85
star
41

coinbase-commerce-python

Coinbase Commerce Python
Python
77
star
42

CBTabViewExample

TypeScript
69
star
43

coinbase-bitmonet-sdk

DEPRECATED — Library to accept bitcoin payments in your Android App
Java
62
star
44

chainstorage

The File System For a Multi-Blockchain World
Go
61
star
45

self-service-iam

DEPRECATED — Self Service AWS IAM Policies for dev at scale
JavaScript
58
star
46

coinbase-wordpress

DEPRECATED — Coinbase plugin/widget for Wordpress
57
star
47

coinbase-commerce-woocommerce

Accept Bitcoin on your WooCommerce-powered website.
PHP
55
star
48

barbar

DEPRECATED — OSX crypto-currency price ticker
Swift
53
star
49

demeter

DEPRECATED — Security Group Management For AWS
Ruby
52
star
50

verifications

📜 "Coinbase Verifications" is a set of Coinbase-verified onchain attestations that enable access to apps and other onchain benefits.
Solidity
50
star
51

coinbase-exchange-node

DEPRECATED — Use gdax-node
JavaScript
46
star
52

cadence-ruby

Ruby SDK for Cadence
Ruby
44
star
53

commerce-onchain-payment-protocol

Solidity
41
star
54

protoc-gen-rbi

Protobuf compiler plugin that generates Sorbet .rbi "Ruby Interface" files.
Go
38
star
55

coinbase-woocommerce

DEPRECATED — Accept Bitcoin on your WooCommerce-powered website.
38
star
56

coinbase-advanced-py

The Advanced API Python SDK is a Python package that makes it easy to interact with the Coinbase Advanced API. The SDK handles authentication, HTTP connections, and provides helpful methods for interacting with the API.
Python
37
star
57

mesh-ecosystem

Repository of all open source Rosetta implementations and SDKs
33
star
58

master_lock

Inter-process locking library using Redis.
Ruby
31
star
59

coinbase-commerce-ruby

Coinbase Commerce Ruby Gem
Ruby
30
star
60

watchdog

DEPRECATED -- Github Bot for Datadog codification
Go
28
star
61

bittip

DEPRECATED — Reddit tip bot
JavaScript
27
star
62

maxfuzz

DEPRECATED — Containerized Cloud Fuzzing
C
26
star
63

cash-addr

Utility to convert between base58 and CashAddr BCH addresses.
Ruby
25
star
64

rules_ruby

Bazel Ruby Rules
Starlark
24
star
65

mesh-geth-sdk

go-ethereum based sdk for Rosetta API
Go
23
star
66

gtt-ui

DEPRECATED
JavaScript
22
star
67

btcexport

Export process for Bitcoin blockchain data to CSV
Go
22
star
68

bchd-explorer

Vue
21
star
69

redisbetween

Go
20
star
70

baseca

Go
18
star
71

coinbase-magento

DEPRECATED — Accept Bitcoin on your Magento-powered website.
17
star
72

coinbase-commerce-whmcs

Coinbase Commerce module for WHMCS
PHP
16
star
73

coinbase-android-sdk-example

DEPRECATED — Example android app leveraging the coinbase android sdk
Java
15
star
74

coinbase-nft-floor-price

Coinbase NFT floor price estimate model
Python
15
star
75

coinbase-spree

DEPRECATED — Accept bitcoin payments on your Spree store with Coinbase.
15
star
76

service_variables

Service level variables backed by Redis - useful for service wide configuration.
Ruby
12
star
77

solidity-workshop

JavaScript
12
star
78

omniauth-coinbase

DEPRECATED — Coinbase OAuth 2 Strategy for Omniauth
Ruby
12
star
79

coinbase-javascript-sdk

DEPRECATED
JavaScript
11
star
80

coinbase-commerce-prestashop

DEPRECATED — Official Coinbase Commerce Prestashop Payment Module
PHP
11
star
81

wrapped-tokens-os

TypeScript
11
star
82

coinbase-cloud-sdk-js

TypeScript
11
star
83

step-asg-deployer

Deprecated, renamed and maintained at https://github.com/coinbase/odin
Go
10
star
84

eip-token-upgrade

Solidity
10
star
85

mkr-vote-proxy

Cold storage-friendly voting for MKR tokens
Solidity
10
star
86

salus

We would like to request that all contributors please clone a *fresh copy* of this repository since the September 21st maintenance.
HTML
9
star
87

chainsformer

Go
9
star
88

coinbase-magento2

DEPRECATED: Accept Bitcoin on your Magento2-powered website.
8
star
89

code-of-conduct

Code of conduct for open source projects managed by Coinbase
8
star
90

coinbase-commerce-opencart

DEPRECATED — Coinbase Commerce Integration For Opencart
PHP
8
star
91

magic-spend

Solidity
8
star
92

chainnode

Go
7
star
93

waas-proxy-server

Go
7
star
94

client-analytics

TypeScript
7
star
95

node-process-lock

DEPRECATED — Simple process locking using Redis.
JavaScript
7
star
96

coinbase-commerce-magento

DEPRECATED — Coinbase Commerce Payment Gateway For Magento 2
PHP
7
star
97

coinbase-commerce-gravity-forms

DEPRECATED — Official Coinbase Commerce Payment Gateway For Gravity Forms
PHP
7
star
98

paymaster-bundler-examples

7
star
99

coinbase-zencart

DEPRECATED — Accept Bitcoin on your Zen Cart-powered website.
6
star
100

demeter-example

DEPRECATED — Demeter
6
star