UNPKG

20.8 kBMarkdownView Raw
1<!-- shared header START -->
2
3<p align="center">
4 <a href="https://www.contentful.com/developers/docs/references/content-management-api/">
5 <img alt="Contentful Logo" title="Contentful" src="images/contentful-icon.png" width="150">
6 </a>
7</p>
8
9<h1 align='center'>Content Management API</h1>
10
11<h3 align="center">JavaScript</h3>
12
13<p align="center">
14 <a href="README.md">Readme</a> ·
15 <a href="SETUP.md">Setup</a> ·
16 <a href="MIGRATION.md">Migration</a> ·
17 <a href="CHANGELOG.md">Changelog</a> ·
18 <a href="CONTRIBUTING.md">Contributing</a>
19</p>
20
21<p align="center">
22 <a href="https://www.contentful.com/slack/">
23 <img src="https://img.shields.io/badge/-Join%20Community%20Slack-2AB27B.svg?logo=slack&maxAge=31557600" alt="Join Contentful Community Slack">
24 </a>
25</p>
26
27<!-- shared header END -->
28
29## Introduction
30
31[![Build Status](https://circleci.com/gh/contentful/contentful-management.js.svg?style=svg)](https://circleci.com/gh/contentful/contentful-management.js)
32[![npm](https://img.shields.io/npm/v/contentful-management.svg)](https://www.npmjs.com/package/contentful-management)
33[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
34[![npm downloads](https://img.shields.io/npm/dm/contentful-management.svg)](http://npm-stat.com/charts.html?package=contentful-management)
35[![gzip bundle size](http://img.badgesize.io/https://unpkg.com/contentful-management/dist/contentful-management.browser.min.js?compression=gzip)](https://unpkg.com/contentful-management/dist/contentful-management.browser.min.js)
36
37**What is Contentful?**
38
39[Contentful](https://www.contentful.com) provides a content infrastructure for digital teams to power content in websites, apps, and devices. Unlike a CMS, Contentful was built to integrate with the modern software stack. It offers a central hub for structured content, powerful management and delivery APIs, and a customizable web app that enable developers and content creators to ship digital products faster.
40
41<details>
42<summary>Table of contents</summary>
43
44<!-- TOC -->
45
46- [Features](#features)
47- [Supported Environments](#supported-environments)
48- [Getting Started](#getting-started)
49 - [Installation](#installation)
50 - [Node](#node-)
51 - [Browser](#browser-)
52 - [Typings](#typings)
53 - [Authentication](#authentication)
54 - [Using ES6 import](#using-es6-import)
55 - [Your first Request](#your-first-request)
56 - [Alternative plain API](#alternative-plain-api)
57- [App Framework](#app-framework)
58- [Troubleshooting](#troubleshooting)
59- [Documentation/References](#documentationreferences)
60 - [Configuration](#configuration)
61 - [Reference Documentation](#reference-documentation)
62 - [Contentful Javascript resources](#contentful-javascript-resources)
63 - [REST API reference](#rest-api-reference)
64- [Versioning](#versioning)
65- [Reach out to us](#reach-out-to-us)
66- [Get involved](#get-involved)
67- [License](#license)
68- [Code of Conduct](#code-of-conduct)
69
70<!-- /TOC -->
71</details>
72
73## Features
74
75- Content management and retrieval through Contentful's [Content Management API](https://www.contentful.com/developers/docs/references/content-management-api/).
76- Built in rate limiting with recovery procedures
77- Asset processing helpers
78
79## Supported environments
80
81Browsers and Node.js:
82
83- Chrome
84- Firefox
85- Edge
86- Safari
87- node.js (LTS)
88
89Other browsers should also work, but at the moment we're only running automated tests on the browsers and Node.js versions specified above.
90
91# Getting started
92
93To get started with the Contentful Management JS library you'll need to install it, and then get credentials which will allow you to access your content in Contentful.
94
95- [Installation](#installation)
96- [Authentication](#authentication)
97- [Using ES6 import](#using-es6-import)
98- [Your first request](#your-first-request)
99- [Troubleshooting](#troubleshooting)
100- [Documentation/References](#documentationreferences)
101
102## Installation
103
104### Node:
105
106Using [npm](http://npmjs.org):
107
108```sh
109npm install contentful-management
110```
111
112Using [yarn](https://yarnpkg.com/lang/en/):
113
114```sh
115yarn add contentful-management
116```
117
118### Browser:
119
120For browsers, we recommend to download the library via npm or yarn to ensure 100% availability.
121
122If you'd like to use a standalone built file you can use the following script tag or download it from [jsDelivr](https://www.jsdelivr.com/package/npm/contentful-management), under the `dist` directory:
123
124```html
125<script src="https://cdn.jsdelivr.net/npm/contentful-management@latest/dist/contentful-management.browser.min.js"></script>
126```
127
128**It's not recommended to use the above URL for production.**
129
130Using `contentful@latest` will always get you the latest version, but you can also specify a specific version number:
131
132```html
133<!-- Avoid using the following url for production. You can not rely on its availability. -->
134<script src="https://cdn.jsdelivr.net/npm/contentful-management@7.3.0/dist/contentful-management.browser.min.js"></script>
135```
136
137The Contentful Management library will be accessible via the `contentfulManagement` global variable.
138
139Check the [releases](https://github.com/contentful/contentful-management.js/releases) page to know which versions are available.
140
141## Typings
142
143This library also comes with typings to use with typescript.
144
145## Authentication
146
147To get content from Contentful, an app should authenticate with an OAuth bearer token.
148
149If you want to use this library for a simple tool or a local app that you won't redistribute or make available to other users, you can get an API key for the Management API at our [Authentication page](https://www.contentful.com/developers/docs/references/authentication/).
150
151If you'd like to create an app which would make use of this library but that would be available for other users, where they could authenticate with their own Contentful credentials, make sure to also check out the section about [Creating an OAuth Application](https://www.contentful.com/developers/docs/references/authentication/#creating-an-oauth-20-application)
152
153## Using ES6 import
154
155You can use the es6 import with the library as follows
156
157```js
158// import createClient directly
159import contentful from 'contentful-management'
160const client = contentful.createClient(
161 {
162 // This is the access token for this space. Normally you get the token in the Contentful web app
163 accessToken: 'YOUR_ACCESS_TOKEN',
164 },
165 { type: 'plain' }
166)
167//....
168```
169
170## Your first request
171
172Beginning with `contentful-management@7` this library provides a client which exposes all CMA endpoints in a simple flat API surface, as opposed to the waterfall structure exposed by legacy versions of the SDK.
173
174```javascript
175const contentful = require('contentful-management')
176const plainClient = contentful.createClient(
177 {
178 accessToken: 'YOUR_ACCESS_TOKEN',
179 },
180 { type: 'plain' }
181)
182
183const environment = await plainClient.environment.get({
184 spaceId: '<space_id>',
185 environmentId: '<environment_id>',
186})
187
188const entries = await plainClient.entry.getMany({
189 spaceId: '123',
190 environmentId: '',
191 query: {
192 skip: 10,
193 limit: 100,
194 },
195})
196
197// With scoped space and environment
198const scopedPlainClient = contentful.createClient(
199 {
200 accessToken: 'YOUR_ACCESS_TOKEN',
201 },
202 {
203 type: 'plain',
204 defaults: {
205 spaceId: '<space_id>',
206 environmentId: '<environment_id>',
207 },
208 }
209)
210
211// entries from '<space_id>' & '<environment_id>'
212const entries = await scopedPlainClient.entry.getMany({
213 query: {
214 skip: 10,
215 limit: 100,
216 },
217})
218```
219
220You can try and change the above example on [Runkit](https://npm.runkit.com/contentful-management).
221
222The benefits of using the "plain" version of the client, over the legacy version, are:
223
224- The ability to reach any possible CMA endpoint without the necessity to call any async functions beforehand.
225 - It's especially important if you're using this CMA client for non-linear scripts (for example, a complex Front-end application)
226- All returned objects are simple Javascript objects without any wrappers. They can be easily serialized without an additional `toPlainObject` function call.
227- The ability to scope CMA client instance to a specific `spaceId`, `environmentId`, and `organizationId` when initializing the client.
228 - You can pass a concrete values to `defaults` and omit specifying these params in actual CMA methods calls.
229
230## Legacy Client Interface
231
232The following code snippet is an example of the legacy client interface, which reads and writes data as a sequence of nested requests:
233
234```js
235const contentful = require('contentful-management')
236const client = contentful.createClient({
237 accessToken: 'YOUR_ACCESS_TOKEN',
238})
239
240// Get a space with the specified ID
241client.getSpace('spaceId').then((space) => {
242 // Get an environment within the space
243 space.getEnvironment('master').then((environment) => {
244 // Get entries from this environment
245 environment.getEntries().then((entries) => {
246 console.log(entries.items)
247 })
248 // Get a content type
249 environment.getContentType('product').then((contentType) => {
250 // Update its name
251 contentType.name = 'New Product'
252 contentType.update().then((updatedContentType) => {
253 console.log('Update was successful')
254 })
255 })
256 })
257})
258```
259
260## App Framework
261
262Starting [`@contentful/app-sdk@4`](https://github.com/contentful/app-sdk) you can use this client to make requests
263from your [apps built for Contentful](https://www.contentful.com/developers/docs/extensibility/app-framework/).
264
265A dedicated [Adapter](https://github.com/contentful/contentful-management.js/blob/2350b47053459694b21b19c71025632fe57815cc/lib/common-types.ts#L493-L495)
266grants your apps access to the supported space-environment scoped entities without compromising on security as you won't
267need to expose a management token, and without coding any additional backend middleware.
268
269```javascript
270const contentfulApp = require('@contentful/app-sdk')
271const contentful = require('contentful-management')
272
273contentfulApp.init((sdk) => {
274 const cma = contentful.createClient(
275 { apiAdapter: sdk.cmaAdapter },
276 {
277 type: 'plain',
278 defaults: {
279 environmentId: sdk.ids.environmentAlias ?? sdk.ids.environment,
280 spaceId: sdk.ids.space,
281 },
282 }
283 )
284
285 // ...rest of initialization code
286})
287```
288
289> **Please Note**
290>
291> Requests issued by the App SDK adapter will count towards the same rate limiting quota as the ones made by other APIs
292> exposed by App SDK (e.g., Space API). Ultimately, they will all fall into the same bucket as the calls performed by
293> the host app (i.e., Contentful web app, Compose, or Launch).
294
295## Troubleshooting
296
297- **I can't Install the package via npm** - Check your internet connection - It is called `contentful-management` and not `contenful-management` ¯\\\_(ツ)\_
298- **Can I use the library in react native projects** - Yes it is possible
299- **I get the error: Unable to resolve module `http`** - Our library is supplied as node and browser version. Most non-node environments, like React Native, act like a browser. To force using of the browser version, you can require it via: `const { createClient } = require('contentful-management/dist/contentful-management.browser.min.js')`
300- **I am not sure what payload to send when creating and entity (Asset/Entity/ContentType etc...)** - Check the Content Management API [docs](https://www.contentful.com/developers/docs/references/content-management-api/) or the examples in the reference [docs](https://contentful.github.io/contentful-management.js) - Feel free to open an issue if you didn't find what you need in the above links
301- 😱 **something is wrong what should I do** - If it is a bug related to the code create a GitHub issue and make sure to remove any credential for your code before sharing it. - If you need to share your credentials, for example you have an issue with your space, please create a support ticket. - Please **do not** share your management token in a GitHub issue
302
303## Documentation/References
304
305To help you get the most out of this library, we've prepared reference documentation, tutorials and other examples that will help you learn and understand how to use this library.
306
307## Configuration
308
309The `createClient` method supports several options you may set to achieve the expected behavior:
310
311```js
312contentful.createClient({
313 ... your config here ...
314})
315```
316
317#### accessToken (required, when `apiAdapter` is not set)
318
319Your CMA access token.
320
321#### host (default: `'api.contentful.com'`)
322
323Set the host used to build the request URI's.
324
325#### hostUpload (default: `'upload.contentful.com'`)
326
327Set the host used to build the upload related request uri's.
328
329#### basePath (default: ``)
330
331This path gets appended to the host to allow request urls like `https://gateway.example.com/contentful/` for custom gateways/proxies.
332
333#### httpAgent (default: `undefined`)
334
335Custom agent to perform HTTP requests. Find further information in the [axios request config documentation](https://github.com/mzabriskie/axios#request-config).
336
337#### httpsAgent (default: `undefined`)
338
339Custom agent to perform HTTPS requests. Find further information in the [axios request config documentation](https://github.com/mzabriskie/axios#request-config).
340
341#### headers (default: `{}`)
342
343Additional headers to attach to the requests. We add/overwrite the following headers:
344
345- Content-Type: `application/vnd.contentful.management.v1+json`
346- X-Contentful-User-Agent: `sdk contentful-management.js/1.2.3; platform node.js/1.2.3; os macOS/1.2.3`
347 (Automatically generated)
348
349#### proxy (default: `undefined`)
350
351Axios proxy configuration. See the [axios request config documentation](https://github.com/mzabriskie/axios#request-config) for further information about the supported values.
352
353#### retryOnError (default: `true`)
354
355By default, this library is retrying requests which resulted in a 500 server error and 429 rate limit response. Set this to `false` to disable this behavior.
356
357#### logHandler (default: `function (level, data) {}`)
358
359Errors and warnings will be logged by default to the node or browser console. Pass your own log handler to intercept here and handle errors, warnings and info on your own.
360
361#### requestLogger (default: `function (config) {}`)
362
363Interceptor called on every request. Takes Axios request config as an arg. Default does nothing. Pass your own function to log any desired data.
364
365#### responseLogger (default: `function (response) {}`)
366
367Interceptor called on every response. Takes Axios response object as an arg. Default does nothing. Pass your own function to log any desired data.
368
369#### apiAdapter (default: `new RestAdapter(configuration)`)
370
371An [`Adapter`](https://github.com/contentful/contentful-management.js/blob/2350b47053459694b21b19c71025632fe57815cc/lib/common-types.ts#L493-L495)
372that can be utilized to issue requests. It defaults to a [`RestAdapter`](https://github.com/contentful/contentful-management.js/blob/b50534c629a8ddc81637170a07bc63477d136cec/lib/adapters/REST/rest-adapter.ts)
373initialized with provided configuration.
374
375> **Please Note**
376>
377> The Adapter will take precedence over the other options. Therefore, ensure you're providing the Adapter all the
378> information it needs to issue the request (e.g., host or auth headers)
379
380#### throttle (default: `0`)
381
382Maximum number of requests per second.
383
384- `1`-`30` (fixed number of limit),
385- `'auto'` (calculated limit based on your plan),
386- `'0%'` - `'100%'` (calculated % limit based on your plan)
387
388### Reference documentation
389
390The [Contentful's JS library reference](https://contentful.github.io/contentful-management.js) documents what objects and methods are exposed by this library, what arguments they expect and what kind of data is returned.
391
392Most methods also have examples which show you how to use them.
393
394You can start by looking at the top level `contentfulManagement` namespace.
395
396The `ContentfulClientAPI` namespace defines the methods at the Client level which allow you to create and get spaces.
397
398The `ContentfulSpaceAPI` namespace defines the methods at the Space level which allow you to create and get entries, assets, content types and other possible entities.
399
400The `Entry`, `Asset` and `ContentType` namespaces show you the instance methods you can use on each of these entities, once you retrieve them from the server.
401
402> From version 1.0.0 onwards, you can access documentation for a specific version by visiting `https://contentful.github.io/contentful-management.js/contentful-management/<VERSION>`
403
404### Contentful JavaScript resources
405
406Read the [Contentful for JavaScript](https://www.contentful.com/developers/docs/javascript/) page for Tutorials, Demo Apps, and more information on other ways of using JavaScript with Contentful
407
408### REST API reference
409
410This library is a wrapper around our Contentful Management REST API. Some more specific details such as search parameters and pagination are better explained on the [REST API reference](https://www.contentful.com/developers/docs/references/content-management-api/), and you can also get a better understanding of how the requests look under the hood.
411
412## Versioning
413
414This project strictly follows [Semantic Versioning](http://semver.org/) by use of [semantic-release](https://github.com/semantic-release/semantic-release).
415
416This means that new versions are released automatically as fixes, features or breaking changes are released.
417
418You can check the changelog on the [releases](https://github.com/contentful/contentful-management.js/releases) page.
419
420## Reach out to us
421
422### You have questions about how to use this library?
423
424- Reach out to our community
425 forum: [![Contentful Community Forum](https://img.shields.io/badge/-Join%20Community%20Forum-3AB2E6.svg?logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA1MiA1OSI+CiAgPHBhdGggZmlsbD0iI0Y4RTQxOCIgZD0iTTE4IDQxYTE2IDE2IDAgMCAxIDAtMjMgNiA2IDAgMCAwLTktOSAyOSAyOSAwIDAgMCAwIDQxIDYgNiAwIDEgMCA5LTkiIG1hc2s9InVybCgjYikiLz4KICA8cGF0aCBmaWxsPSIjNTZBRUQyIiBkPSJNMTggMThhMTYgMTYgMCAwIDEgMjMgMCA2IDYgMCAxIDAgOS05QTI5IDI5IDAgMCAwIDkgOWE2IDYgMCAwIDAgOSA5Ii8+CiAgPHBhdGggZmlsbD0iI0UwNTM0RSIgZD0iTTQxIDQxYTE2IDE2IDAgMCAxLTIzIDAgNiA2IDAgMSAwLTkgOSAyOSAyOSAwIDAgMCA0MSAwIDYgNiAwIDAgMC05LTkiLz4KICA8cGF0aCBmaWxsPSIjMUQ3OEE0IiBkPSJNMTggMThhNiA2IDAgMSAxLTktOSA2IDYgMCAwIDEgOSA5Ii8+CiAgPHBhdGggZmlsbD0iI0JFNDMzQiIgZD0iTTE4IDUwYTYgNiAwIDEgMS05LTkgNiA2IDAgMCAxIDkgOSIvPgo8L3N2Zz4K&maxAge=31557600)](https://support.contentful.com/)
426- Jump into our community slack
427 channel: [![Contentful Community Slack](https://img.shields.io/badge/-Join%20Community%20Slack-2AB27B.svg?logo=slack&maxAge=31557600)](https://www.contentful.com/slack/)
428
429### You found a bug or want to propose a feature?
430
431- File an issue here on GitHub: [![File an issue](https://img.shields.io/badge/-Create%20Issue-6cc644.svg?logo=github&maxAge=31557600)](https://github.com/contentful/contentful-management.js/issues/new).
432 Make sure to remove any credential from your code before sharing it.
433
434### You need to share confidential information or have other questions?
435
436- File a support ticket at our Contentful Customer
437 Support: [![File support ticket](https://img.shields.io/badge/-Submit%20Support%20Ticket-3AB2E6.svg?logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA1MiA1OSI+CiAgPHBhdGggZmlsbD0iI0Y4RTQxOCIgZD0iTTE4IDQxYTE2IDE2IDAgMCAxIDAtMjMgNiA2IDAgMCAwLTktOSAyOSAyOSAwIDAgMCAwIDQxIDYgNiAwIDEgMCA5LTkiIG1hc2s9InVybCgjYikiLz4KICA8cGF0aCBmaWxsPSIjNTZBRUQyIiBkPSJNMTggMThhMTYgMTYgMCAwIDEgMjMgMCA2IDYgMCAxIDAgOS05QTI5IDI5IDAgMCAwIDkgOWE2IDYgMCAwIDAgOSA5Ii8+CiAgPHBhdGggZmlsbD0iI0UwNTM0RSIgZD0iTTQxIDQxYTE2IDE2IDAgMCAxLTIzIDAgNiA2IDAgMSAwLTkgOSAyOSAyOSAwIDAgMCA0MSAwIDYgNiAwIDAgMC05LTkiLz4KICA8cGF0aCBmaWxsPSIjMUQ3OEE0IiBkPSJNMTggMThhNiA2IDAgMSAxLTktOSA2IDYgMCAwIDEgOSA5Ii8+CiAgPHBhdGggZmlsbD0iI0JFNDMzQiIgZD0iTTE4IDUwYTYgNiAwIDEgMS05LTkgNiA2IDAgMCAxIDkgOSIvPgo8L3N2Zz4K&maxAge=31557600)](https://www.contentful.com/support/)
438
439## Get involved
440
441We appreciate any help on our repositories. For more details about how to contribute see our [CONTRIBUTING.md](https://github.com/contentful/contentful-management.js/blob/master/CONTRIBUTING.md) document.
442
443## License
444
445This repository is published under the [MIT](LICENSE) license.
446
447## Code of Conduct
448
449We want to provide a safe, inclusive, welcoming, and harassment-free space and experience for all participants, regardless of gender identity and expression, sexual orientation, disability, physical appearance, socioeconomic status, body size, ethnicity, nationality, level of experience, age, religion (or lack thereof), or other identity markers.
450
451[Read our full Code of Conduct](https://www.contentful.com/developers/code-of-conduct/).