Getting Started with Contentful and Python
This guide will show you how to get started using our Python client library to consume content.
Contentful’s Content Delivery API (CDA) is a read-only API for retrieving content from Contentful. All content, both JSON and binary, is fetched from the server closest to a user’s location by using our global CDN.
We publish client libraries for various languages to make developing applications easier.
Requirements
This tutorial assumes that you understand the Contentful data model.
Authentication
For every request, clients need to provide an API key, which is created per space and used to delimit applications and content classes.
You can create an access token using the Contentful web app or the Content Management API.
Installation
Install the ‘contentful’ client with pip:
virtualenv you may have to use sudo to install the client library.Or add the client library to your requirements.txt file:
And run pip install -r requirements.txt to install the client and all dependencies.
Setting up the Contentful client
Once you have installed the package, you can use it inside your application.
Initialize the client
You need an API key and a space ID to initialize a client. You can use the API key and space ID pre-filled below from our example space or replace them with your own values.
Getting your content
Contentful separates content between entries, which contain your data and relationships with other content or images, and assets, which represent static content, like images, and are served as files. Read more in our content model guide.
Entries
With the client created, you can now start consuming data from the CDA.
For example, to request all entries in a space:
Or to request a single entry:
You can specify any of the query parameters accepted by the API, for example:
Using your entry as a Python object
Once you have your entry, you can use it as a Python object that follows standard Python conventions:
You can form complicated queries and interaction with your entries:
In this example you added the include: 2 parameter, which allows the API to resolve links to other related entries.
Using assets
You query assets in a similar way to entries, but the CDA offers more specific features, such as filtering by the type of file. You can also use our Images API, that allows you to manipulate images as you retrieve them.
To query a single asset:
To query all assets in a space: