• Stars
    star
    155
  • Rank 240,864 (Top 5 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created over 13 years ago
  • Updated over 3 years ago

Reviews

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

Repository Details

CARTO Python client

carto-python

Documentation Status

Python SDK for Carto's APIs:

carto-python is a full, backwards incompatible rewrite of the deprecated cartodb-python SDK. Since the initial rewrite, carto-python has been loaded with a lot of new features, not present in old cartodb-python.

Installation

You can install carto-python by cloning this repository or by using Pip:

pip install carto

If you want to use the development version, you can install directly from github:

pip install -e git+git://github.com/CartoDB/carto-python.git#egg=carto

If using, the development version, you might want to install Carto's dependencies as well:

pip install -r requirements.txt

Test Suite

Create a secret.py from secret.py.example, fill the variables, cd into the repo folder, create and enable virtualenv, install pytest and run tests:

cd carto-python
virtualenv env
source env/bin/activate
pip install -e .
pip install -r test_requirements.txt
pip install pytest
py.test tests

Authentication

Before making API calls, we need to define how those calls are going to be authenticated. Currently, we support two different authentication methods: unauthenticated and API key based. Therefore, we first need to create an authentication client that will be used when instantiating the Python classes that deal with API requests.

For unauthenticated requests, we need to create a NoAuthClient object:

from carto.auth import NoAuthClient

USERNAME="type here your username"
USR_BASE_URL = "https://{user}.carto.com/".format(user=USERNAME)
auth_client = NoAuthClient(base_url=USR_BASE_URL)

For API key authenticated requests, we need to create an APIKeyAuthClient instance:

from carto.auth import APIKeyAuthClient

USERNAME="type here your username"
USR_BASE_URL = "https://{user}.carto.com/".format(user=USERNAME)
auth_client = APIKeyAuthClient(api_key="myapikey", base_url=USR_BASE_URL)

API key is mandatory for all API requests except for sending SQL queries to public datasets.

The base_url parameter must include the user and or the organization

BASE_URL = "https://{organization}.carto.com/user/{user}/". \
    format(organization=ORGANIZATION,
           user=USERNAME)
USR_BASE_URL = "https://{user}.carto.com/".format(user=USERNAME)

Additionally, see test_auth.py for supported formats for the base_url parameter.

For a detailed description of the rest of parameters both constructors accept, please take a look at the documentation of the source code.

SQL API

Making requests to the SQL API is pretty straightforward:

from carto.sql import SQLClient

sql = SQLClient(auth_client)

try:
    data = sql.send('select * from mytable')
except CartoException as e:
    print("some error ocurred", e)

print data['rows']

Please refer to the source code documentation to find out about the rest of the parameters accepted by the constructor and the send method. In particular, the send method allows you to control the format of the results.

Batch SQL requests

For long lasting SQL queries you can use the batch SQL API.

from carto.sql import BatchSQLClient

LIST_OF_SQL_QUERIES = []

batchSQLClient = BatchSQLClient(auth_client)
createJob = batchSQLClient.create(LIST_OF_SQL_QUERIES)

print(createJob['job_id'])

The BatchSQLClient is asynchronous, but it offers methods to check the status of a job, update it or cancel it:

# check the status of a job after it has been created and you have the job_id
readJob = batchSQLClient.read(job_id)

# update the query of a batch job
updateJob = batchSQLClient.update(job_id, NEW_QUERY)

# cancel a job given its job_id
cancelJob = batchSQLClient.cancel(job_id)

COPY queries

COPY queries allow you to use the PostgreSQL COPY command for efficient streaming of data to and from CARTO.

Here is a basic example of its usage:

from carto.sql import SQLClient
from carto.sql import CopySQLClient

sql_client = SQLClient(auth_client)
copy_client = CopySQLClient(auth_client)

# Create a destination table for the copy with the right schema
sql_client.send("""
    CREATE TABLE IF NOT EXISTS copy_example (
      the_geom geometry(Geometry,4326),
      name text,
      age integer
    )
    """)
sql_client.send("SELECT CDB_CartodbfyTable(current_schema, 'copy_example')")

# COPY FROM a csv file in the filesytem
from_query = 'COPY copy_example (the_geom, name, age) FROM stdin WITH (FORMAT csv, HEADER true)'
result = copy_client.copyfrom_file_path(from_query, 'copy_from.csv')

# COPY TO a file in the filesystem
to_query = 'COPY copy_example TO stdout WITH (FORMAT csv, HEADER true)'
copy_client.copyto_file_path(to_query, 'export.csv')

Here's an equivalent, more pythonic example of the COPY FROM, using a file object:

with open('copy_from.csv', 'rb') as f:
    copy_client.copyfrom_file_object(from_query, f)

And here is a demonstration of how to generate and stream data directly (no need for a file at all):

def rows():
    # note the \n to delimit rows
    yield bytearray(u'the_geom,name,age\n', 'utf-8')
    for i in range(1,80):
        row = u'SRID=4326;POINT({lon} {lat}),{name},{age}\n'.format(
            lon = i,
            lat = i,
            name = 'fulano',
            age = 100 - i
        )
        yield bytearray(row, 'utf-8')
copy_client.copyfrom(from_query, rows())

For more examples on how to use the SQL API, please refer to the examples folder or the API docs.

Import API

You can import local or remote datasets into CARTO like this:

from carto.datasets import DatasetManager

# write here the path to a local file or remote URL
LOCAL_FILE_OR_URL = ""

dataset_manager = DatasetManager(auth_client)
dataset = dataset_manager.create(LOCAL_FILE_OR_URL)

The Import API is asynchronous, but the DatasetManager waits a maximum of 150 seconds for the dataset to be uploaded, so once it finishes the dataset has been created in CARTO.

Import a sync dataset

You can do it in the same way as a regular dataset, just include a sync_time parameter with a value >= 900 seconds

from carto.datasets import DatasetManager

# how often to sync the dataset (in seconds)
SYNC_TIME = 900
# write here the URL for the dataset to sync
URL_TO_DATASET = ""

dataset_manager = DatasetManager(auth_client)
dataset = dataset_manager.create(URL_TO_DATASET, SYNC_TIME)

Alternatively, if you need to do further work with the sync dataset, you can use the SyncTableJobManager

from carto.sync_tables import SyncTableJobManager
import time

# how often to sync the dataset (in seconds)
SYNC_TIME = 900
# write here the URL for the dataset to sync
URL_TO_DATASET = ""

syncTableManager = SyncTableJobManager(auth_client)
syncTable = syncTableManager.create(URL_TO_DATASET, SYNC_TIME)

# return the id of the sync
sync_id = syncTable.get_id()

while(syncTable.state != 'success'):
    time.sleep(5)
    syncTable.refresh()
    if (syncTable.state == 'failure'):
        print('The error code is: ' + str(syncTable.error_code))
        print('The error message is: ' + str(syncTable.error_message))
        break

# force sync
syncTable.refresh()
syncTable.force_sync()

Get a list of all the current import jobs

from carto.file_import import FileImportJobManager

file_import_manager = FileImportJobManager(auth_client)
file_imports = file_import_manager.all()

Get all the datasets

from carto.datasets import DatasetManager

dataset_manager = DatasetManager(auth_client)
datasets = dataset_manager.all()

Get a specific dataset

from carto.datasets import DatasetManager

# write here the ID of the dataset to retrieve
DATASET_ID = ""

dataset_manager = DatasetManager(auth_client)
dataset = dataset_manager.get(DATASET_ID)

Update the properties of a dataset (non-public API)

from carto.datasets import DatasetManager
from carto.permissions import PRIVATE, PUBLIC, LINK

# write here the ID of the dataset to retrieve
DATASET_ID = ""

dataset_manager = DatasetManager(auth_client)
dataset = dataset_manager.get(DATASET_ID)

# make the dataset PUBLIC
dataset.privacy = PUBLIC
dataset.save()

Delete a dataset

from carto.datasets import DatasetManager

# write here the ID of the dataset to retrieve
DATASET_ID = ""

dataset_manager = DatasetManager(auth_client)
dataset = dataset_manager.get(DATASET_ID)
dataset.delete()

Export a CARTO visualization (non-public API)

from carto.visualizations import VisualizationManager

# write here the name of the map to export
MAP_NAME = ""

visualization_manager = VisualizationManager(auth_client)
visualization = visualization_manager.get(MAP_NAME)

url = visualization.export()

# the URL points to a .carto file
print(url)

Please refer to the source code documentation and the examples folder to find out about the rest of the parameters accepted by constructors and methods.

Maps API

The Maps API allows to create and instantiate named and anonymous maps:

from carto.maps import NamedMapManager, NamedMap
import json

# write the path to a local file with a JSON named map template
JSON_TEMPLATE = ""

named_map_manager = NamedMapManager(auth_client)
named_map = NamedMap(named_map_manager.client)

with open(JSON_TEMPLATE) as named_map_json:
    template = json.load(named_map_json)

# Create named map
named = named_map_manager.create(template=template)
from carto.maps import AnonymousMap
import json

# write the path to a local file with a JSON named map template
JSON_TEMPLATE = ""

anonymous = AnonymousMap(auth_client)
with open(JSON_TEMPLATE) as anonymous_map_json:
    template = json.load(anonymous_map_json)

# Create anonymous map
anonymous.instantiate(template)

Instantiate a named map

from carto.maps import NamedMapManager, NamedMap
import json

# write the path to a local file with a JSON named map template
JSON_TEMPLATE = ""

# write here the ID of the named map
NAMED_MAP_ID = ""

# write here the token you set to the named map when created
NAMED_MAP_TOKEN = ""

named_map_manager = NamedMapManager(auth_client)
named_map = named_map_manager.get(NAMED_MAP_ID)

with open(JSON_TEMPLATE) as template_json:
    template = json.load(template_json)

named_map.instantiate(template, NAMED_MAP_TOKEN)

Work with named maps

from carto.maps import NamedMapManager, NamedMap

# write here the ID of the named map
NAMED_MAP_ID = ""

# get the named map created
named_map = named_map_manager.get(NAMED_MAP_ID)

# update named map
named_map.view = None
named_map.save()

# delete named map
named_map.delete()

# list all named maps
named_maps = named_map_manager.all()

For more examples on how to use the Maps API, please refer to the examples folder or the API docs.

API Documentation

API documentation is written with Sphinx. To build the API docs:

pip install sphinx
pip install sphinx_rtd_theme
cd doc
make html

Docs are generated inside the doc/build/hmtl folder. Please refer to them for a complete list of objects, functions and attributes of the carto-python API.

non-public APIs

Non-public APIs may change in the future and will thrown a warnings.warn message when used.

Please be aware if you plan to run them on a production environment.

Refer to the API docs for a list of non-public APIs

Examples

Inside the examples folder there are sample code snippets of the carto-python client.

To run examples, you should need to install additional dependencies:

pip install -r examples/requirements.txt

carto-python examples need to setup environment variables.

  • CARTO_ORG: The name of your organization
  • CARTO_API_URL: The base_url including your user and/or organization
  • CARTO_API_KEY: Your user API key

Please refer to the examples source code for additional info about parameters of each one

More Repositories

1

cartodb

Location Intelligence & Data Visualization tool
JavaScript
2,751
star
2

odyssey.js

Making it easy to merge map and narrative
JavaScript
1,620
star
3

carto.js

CartoDB javascript library
JavaScript
421
star
4

torque

Temporal mapping for CARTO
JavaScript
395
star
5

Windshaft

A Node.js map tile library for PostGIS and torque.js, with CartoCSS styling
JavaScript
307
star
6

cartoframes

CARTO Python package for data scientists
Python
249
star
7

basemap-styles

CARTO basemap public styles
CartoCSS
222
star
8

CartoColor

CartoColors as a node module
JavaScript
212
star
9

analytics-toolbox-core

A set of UDFs and Procedures to extend BigQuery, Snowflake, Redshift, Postgres and Databricks with Spatial Analytics capabilities
JavaScript
188
star
10

mobile-sdk

CARTO Mobile SDK core project
C
170
star
11

carto-vl

CARTO VL: a Javascript library to create vector-based visualizations
JavaScript
128
star
12

Leaflet.CanvasLayer

full screen canvas layer for Leaflet
JavaScript
116
star
13

VECNIK

Render Vector HTML5 maps using CartoDB and Carto as styling language, on top of Leaflet
JavaScript
114
star
14

cartodb-postgresql

PostgreSQL extension for CartoDB
PLpgSQL
109
star
15

data-science-book

Jupyter Notebook
100
star
16

carto-workshop

CARTO training materials
Jupyter Notebook
87
star
17

airship

A design library for building Location Intelligence applications.
JavaScript
75
star
18

Windshaft-cartodb

Windshaft tailored for CARTO
JavaScript
72
star
19

CartoDB-SQL-API

CartoDB SQL API
JavaScript
60
star
20

cartodb-r

R package to interface with CartoDB
R
59
star
21

python-quadkey

native library to manage quadkey in a fast way
C
57
star
22

CartoDB-basemaps

CartoDB basemaps
CartoCSS
54
star
23

crankshaft

CARTO Spatial Analysis extension for PostgreSQL
Python
51
star
24

academy

Academy
HTML
48
star
25

cartodb-nodejs

Node.js package for easy access to CartoDB's APIs
JavaScript
45
star
26

research-public

This repository contains the code and data related to different research initiatives carried out at CARTO by the Data Science team
Jupyter Notebook
45
star
27

bigmetadata

Python
43
star
28

real-time-map

CSS
40
star
29

carto-react-template

CARTO for React. The best way to develop Location Intelligence (LI) Apps usign CARTO platform and React
JavaScript
39
star
30

carto-react

CARTO for React packages
JavaScript
36
star
31

grainstore

Generate Mapnik MML & XML for single postgis tables with style persistance.
JavaScript
36
star
32

deep-insights.js

Create powerful dashboards using CARTO
JavaScript
34
star
33

mobile-android-samples

Android sample for CARTO Mobile SDK
Java
34
star
34

d3.cartodb

Client-side rendering of CartoDB visualisations with d3
JavaScript
30
star
35

mobile-ios-samples

iOS mobile app with CARTO Mobile SDK
Swift
28
star
36

torque-tiles

Torque Tiles Specification
28
star
37

turbo-carto

CartoCSS preprocessor
JavaScript
28
star
38

carto-selfhosted

Deploy CARTO in a self hosted environment
Shell
26
star
39

tiles3d-demo

JavaScript
25
star
40

data-services

CARTO internal geocoder PostgreSQL extension
Shell
25
star
41

cartodb-rb-client

Ruby client for cartodb API
Ruby
24
star
42

labs-postgresql

23
star
43

cartodb-pluto

PLUTO Data Service
23
star
44

dataservices-api

The CARTO Data Services API
PLpgSQL
22
star
45

carto-print

A Python module to export images at any resolution, size and bounding box from a CARTO named map:
Python
19
star
46

cartonik

Render maps with @carto/mapnik
JavaScript
18
star
47

training

CartoDB Workshops
HTML
17
star
48

camshaft

Analysis library to create data views from queries
JavaScript
17
star
49

cesium-cartodb

JavaScript
16
star
50

mobile-dotnet-samples

CARTO SDK samples for Xamarin Android, iOS and UWP .NET
C#
16
star
51

raster-loader

Python
15
star
52

cdb-manager

JavaScript
15
star
53

cloud-next

Demo Google Maps Vector, Deck.gl and CARTO
JavaScript
14
star
54

bcn_traffic_map

Dynamically web map example using CartoDB: Barcelona Traffic Map
Python
14
star
55

carto-etl

Python
13
star
56

mapboxgl-draw-rectangle-drag

A Mapbox GL Draw plugin to create a rectangle via click & drag
JavaScript
13
star
57

poc-databricks

CARTO Analytics Toolbox for Databricks provides geospatial functionality leveraging the Geomesa SparkSQL capabilities.
Scala
13
star
58

labs-multilayer

HTML
12
star
59

pg_schema_triggers

PostgreSQL 9.3+ Schema Triggers extension
C
11
star
60

GoT

The Geom of Thrones
JavaScript
11
star
61

QuadGrid

Quadgrid for GDPR compliance
PLpgSQL
11
star
62

osm

CartoDB OSM installation scripts
Shell
10
star
63

cartodb-java-client

java client for cartodb SQL API
Java
10
star
64

torque.histogram

widget to see a histogram of a torque map
JavaScript
9
star
65

cartodb-publishing-templates

CSS
9
star
66

showcase-maps

JavaScript
9
star
67

toolkit

JS library to interact with CARTO APIs in a simple way
TypeScript
9
star
68

carto-waze

Python
8
star
69

node-cartodb-redis

node module to interact with the cartodb redis database
JavaScript
8
star
70

labs-cdbfiddle

An HTML template that takes a viz.json and displays the map, SQL, and CartoCSS in a neat embeddable iframe
HTML
8
star
71

carto-selfhosted-helm

Helm charts for CARTO Self-Hosted
Mustache
8
star
72

carto-for-developers-guides

Documentation to use CARTO with different visualization libraries
TypeScript
8
star
73

labs_vuejs_intro

Vue.js Introductory Workshop
HTML
8
star
74

carto-vl-cluster-workshop

CARTO VL cluster workshop
HTML
6
star
75

SDSC-23-NY

6
star
76

observatory-extension

PLpgSQL
6
star
77

platypus

JavaScript
5
star
78

CartoAssets

Common assets shared across several CARTO repositories
CSS
5
star
79

cartodb.proj

cartodb.js extension to work with non webmercator projections
JavaScript
5
star
80

web-sdk

TypeScript
5
star
81

carto-react-telco-demo

JavaScript
5
star
82

cartodb15-workshop

JavaScript
5
star
83

mobile-tile-packager

Packages data from CARTO map/dataset as mbtiles with vector tiles
JavaScript
5
star
84

torque-gen

Export Torque tiles from local Postgres tables or your CartoDB account
Python
5
star
85

oldweather_wwi

A CartoDB visualization that maps the entire OldWeather dataset of over 1M UK navy locations during the period of WWI.
JavaScript
5
star
86

sdsc-bootcamp-spatial-data-eng

This repository contains the code used in workshop "An introduction to Spatial Data Engineering", in SDS Bootcamps
5
star
87

mobile-external-libs

External libraries needed for CARTO Mobile SDK
C
4
star
88

tangram-cartocss

⛔️ DEPRECATED Transform cartocss into a draw tangram object
JavaScript
4
star
89

zika

Mapping progression, risk factors, and response to the Zika virus
JavaScript
4
star
90

carto-vl-webpack-demo

Simple demo about how to use CARTO VL with webpack
JavaScript
4
star
91

workshop_UCL-CASA

Materials for the workshop at The Bartlett Centre for Advanced Spatial Analysis - UCL
4
star
92

mobile-carto-libs

Internal dependencies for CARTO Mobile SDK
C++
4
star
93

documentation

Main repo for CARTO's documentation.
HTML
4
star
94

node-cartodb-psql

A simple wrapper for node-postgres to work with CartoDB
JavaScript
4
star
95

labs-cartodb2ckan

JavaScript
4
star
96

mobile-sample-data-collection

Location-based mobile data collection with CARTO Mobile SDK
C#
4
star
97

node-redis-mpool

Multi-pool for redis connections
JavaScript
4
star
98

beedumper

A tool to export data from SupportBee ticketing tool
Python
3
star
99

labs-colorscales

Design and test your color scales
JavaScript
3
star
100

tangram.cartodb

⛔️ DEPRECATED A library to render in webgl vector tiles in cartodb.js
JavaScript
3
star