afpnews-api
v3.8.0
Published
Node helper functions to authenticate and fetch AFP Core API
Readme
AfpNews API
A TypeScript client library for the AFP Core API. Provides authentication, document search, notification management, saved filters, and social story retrieval for both Node.js and browser environments.
Installation
Node.js
npm install afpnews-apiimport { ApiCore } from 'afpnews-api'
// or CommonJS
const { ApiCore } = require('afpnews-api')Browser (UMD)
<script src="https://unpkg.com/afpnews-api/dist/bundles/apicore.min.js"></script>Browser (ESM)
import { ApiCore } from 'https://cdn.jsdelivr.net/npm/afpnews-api/dist/bundles/apicore.min.mjs'Prerequisites
You need an API key or client credentials (client ID + secret) to connect. For user-authenticated requests, you also need a username and password.
Quick Start
import { ApiCore } from 'afpnews-api'
// Initialize with client credentials
const afp = new ApiCore({ clientId: 'your-id', clientSecret: 'your-secret' })
// Or with an API key
const afp = new ApiCore({ apiKey: 'your-api-key' })
// Optionally override the base URL
const afp = new ApiCore({ clientId: 'your-id', clientSecret: 'your-secret', baseUrl: 'https://custom-api.afp.com' })Authentication
// Anonymous authentication (uses API key or client credentials)
await afp.authenticate()
// Authenticate with user credentials
await afp.authenticate({ username: 'user', password: 'pass' })
// Listen for token changes
afp.on('tokenChanged', (token) => {
console.log(token)
// { accessToken, refreshToken, tokenExpires, authType }
})
// Token is automatically refreshed when expiredThe token is renewed 30 seconds before it expires, and only once even when several calls need it at the same time (the API invalidates the current access token on refresh, so concurrent refreshes would cancel each other). A call that gets a 401 renews the token and is replayed once. Logging in while a refresh is in flight waits for it, so the refresh cannot overwrite the login token.
Error Handling
Every API failure is thrown as an ApiError:
import { ApiError } from 'afpnews-api'
try {
await afp.search({ query: 'Macron' })
} catch (error) {
if (error instanceof ApiError) {
error.code // AFP error code, or the HTTP status (401, 404, 429…)
error.status // HTTP status of the response
error.type // AFP error type: 'invalid_token', 'invalid_user', 'invalid_client', 'SearchServerException'…
error.expireAt // for a 429: Date when the block ends
}
}- An error payload is detected even when the API sends it with an HTTP
200. - A non-JSON body (an HTML error page, for instance) gives an
ApiError, not aSyntaxError. - Read requests (
search,list,get,mlt,latest…) are retried once on429,502,503and504: after a short random delay for a5xx, or atexpireAtfor a429when the block ends within 10 seconds. A longer429is thrown right away with itsexpireAt. Writes (saved filters, notifications) and token requests are never retried, since a504can hide a request the server already applied.
Latest Documents
Get the most recent documents:
const { count, documents } = await afp.latest({ lang: 'fr', tz: 'Europe/Paris' })
// Parsed into AfpDocument
const { documents } = await afp.latest({ lang: 'fr' }, { parse: true })Searching Documents
Basic Search
const { count, documents } = await afp.search()Search with Parameters
const { count, documents } = await afp.search({
query: 'Macron',
langs: ['fr', 'en'],
dateFrom: '2024-01-01',
dateTo: '2024-12-31',
size: 20,
sortField: 'published',
sortOrder: 'desc',
tz: 'Europe/Paris',
dateGap: '+1HOUR',
startAt: 0,
wantedFacets: { slug: { size: 10, minDocCount: 1 }, country: { size: 5, minDocCount: 1 } },
sort: [{ sortField: 'published', sortOrder: 'desc' }]
})Field Filters
Pass field filters in filters. A value or a list becomes an in condition; an object can combine in and exclude. All filters are combined with AND, together with query:
const { documents } = await afp.search({
query: 'climate',
filters: {
country: 'fra',
urgency: 3,
slug: ['politics', 'economy'],
product: { exclude: ['photo'] }
}
})An object can use several operators; each one becomes a separate condition:
| Operator | Meaning | Example |
|---|---|---|
| in | at least one of the values | { class: { in: ['text', 'picture'] } } |
| exclude | none of the values | { genreid: { exclude: ['afpedtype:docrobot'] } } |
| and | all of the values | { topic: { and: ['alc-fr', 'base-illimitee-afpnews-fr'] } } |
| contains | full-text search in a text field (quote for an exact phrase) | { news: { contains: '"Jean-Vincent Placé"' } } |
| range | interval, bounds included unless fromExcluded / toExcluded | { wordCount: { range: { from: 300, to: 800 } } } |
| exists | field present (true) or absent (false) | { genre: { exists: false } } |
Field names autocomplete in filters, sortField, dateField and langs: the lists come from the AFP documentation's metadata catalogue and are exported as FACET_FIELDS, TEXT_FIELDS and DATE_FIELDS (types FacetField, TextField, DateField, SortField, Lang). Other names are still accepted.
region is not an AFP field: it filters on the countries of one or more AFP regions (france, europe, africa, mena, asia-pacific, north-america, latin-america, antarctica), as a value, a list, or { in, exclude }. It also works in query (region:africa, NOT region:europe). An unknown region throws. The country lists are exported as AFP_REGIONS (type AfpRegion).
afp.search({ filters: { region: ['africa', 'mena'], genre: 'Papier général' } })Two options are related: dateField picks the date field dateFrom / dateTo apply to (published by default), and exactNumFound controls the total count (true: exact; false: none, lighter request; a number: bounded, with relation: 'gt' in the result when the total exceeds it).
const { documents, relation } = await afp.search({
dateField: 'contentCreated',
dateFrom: 'now-7d',
exactNumFound: 1000,
filters: { class: 'text', wordCount: { range: { from: 600 } } }
})Deprecated: filters passed as flat keys (
afp.search({ country: 'fra' })) still work but will be removed in 4.0. Move them intofilters.
Specify Response Fields
Pass an array of field names to limit the returned fields:
const { documents } = await afp.search({}, ['uno', 'title', 'published'])Paginated Search
Use searchAll() to iterate over large result sets automatically:
for await (const doc of afp.searchAll({ size: 5000, query: 'climate' })) {
console.log(doc.uno)
}size is the total number of documents to return; they are fetched in pages of 1000. When the sort field is a date (published by default), pages follow that field (dateField is set to it) and resume right after the last document returned, so no document is returned twice, even when many documents share the same date. With a non-date sort field, pages use startAt. The params object you pass is left untouched.
Query Syntax
The query parameter supports a boolean query DSL:
| Syntax | Example |
|---|---|
| Simple term | Macron |
| Field search | title:Macron |
| AND | Macron AND Merkel |
| OR | title:Macron OR title:Merkel |
| NOT | Macron AND NOT country:fra |
| NOT (shorthand) | -Macron, -title:Macron |
| Parentheses | (title:Macron OR title:Merkel) AND country:fra |
| Field group | title:(Macron OR Merkel) (same as title:Macron OR title:Merkel) |
| Quoted phrase | title:"climate change" |
| Implicit AND | Macron France (space-separated terms) |
| Interval | wordCount:[300 TO 800], wordCount:[600 TO *], published:["2026-09-01T00:00:00Z" TO now] |
| Field present / absent | _exists_:genre, NOT _exists_:genre |
Text fields of the AFP catalogue (news, title, caption, headline, summary…) are searched as text (contains); other fields match exact values. Quote an interval bound that contains : (a time). NOT is not supported on an interval.
Retrieving a Single Document
const document = await afp.get('uno')Parsed Documents (AfpDocument)
By default, get, search and searchAll return raw, untyped API documents. Pass { parse: true } to get the canonical, presentation-agnostic AfpDocument model instead — a TypeScript overload, not a union type, so the return type is inferred correctly in both cases:
import { ApiCore, parseDocument } from 'afpnews-api'
import type { AfpDocument } from 'afpnews-api'
const raw = await afp.get('uno') // unknown
const doc = await afp.get('uno', { parse: true }) // AfpDocument
const { documents } = await afp.search({ query: 'Macron' }, [], { parse: true }) // AfpDocument[]
for await (const doc of afp.searchAll({ query: 'Macron' }, [], { parse: true })) {
console.log(doc.headline)
}
// Or parse a raw document you already fetched:
const doc = parseDocument(raw)AfpDocument reflects the underlying AFP data: class, source, headline, title, creditLine, aspectRatios, paragraphs (segmented, with a stable index for deep-linking), lang, country, city, location (dateline coordinates { lat, lon }, when the API provides them), creator, genre, events, media renditions (with sizeInBytes when the API provides it), and shots for video documents (never throws on a malformed shot list — falls back to []). Fields specific to a subset of class values (caption, shots, topshot, topics, href, script, associatedWith) are only populated for the classes they apply to. parseDocument() throws if the raw input doesn't match the expected shape.
It also exposes what you need to display or apply before publishing a document, when the API provides it:
- Rights and mentions:
copyright(to display to end users),creditLine,disclaimer,rules(e.g.['GERMANY OUT']),usageRights,exclusions,countriesOut,countriesOnly,expires(do not use the document after this date). - Lifecycle:
status,initialStatus,signal,contentWarnings(e.g.{ code: 'cwarn:death', label: 'ViolentGraphicLanguage' }),embargoed. - Classification:
genresandgenreIds(language-independent, prefer them to filter), split intoeditorialTypes(afpedtype:*, several per document) andeditorialAttribute(afpattribute:*, at most one),ratings,channels,mediatopics(IPTC),summary,subheadline,captionContext. topshotistruefor AFP Forum TOPSHOT selections (rating60), not forurgency1 (Flash).- For a video,
captioniscaptionContextwhen present (the same caption without the trailing marker such asSTOCKSHOTS). - Each media has
renditions(images and videos with dimensions, now withrenditionandduration) andcomponents: every component, including those without dimensions such as a webstory's Zip, ZipVideoSet and Mpeg4.
These fields never make parseDocument() fail: a value with an unexpected shape is left undefined.
This is an additive, opt-in change. mlt, latest and searchWithFilter support the same { parse: true } option (see their respective sections below). list returns facet values, not documents, so AfpDocument parsing doesn't apply to it — but its keywords are still a named, zod-validated type: AfpFacetValue ({ name?: string | null; count: number }).
More Like This
Find documents similar to a given one:
const { count, documents } = await afp.mlt('uno', 'en', 10)
// Parsed into AfpDocument (pass `undefined` for size to keep its default of 10)
const { documents } = await afp.mlt('uno', 'en', undefined, { parse: true })Listing Facet Values
Retrieve the most used values for a specific facet:
const { count, keywords } = await afp.list('slug')
// With custom search scope and minimum document count
const { keywords } = await afp.list('country', { dateFrom: 'now-7d', langs: ['en'] }, 5)keywords is typed as AfpFacetValue[] ({ name?: string | null; count: number }), validated at runtime with the same Zod schema.
Field Mapping
Get the API field mapping:
const mapping = await afp.mapping('en')Filter Center
Manage saved search filters.
const fc = afp.filterCenter
// Create a filter
await fc.add('breaking-politics', { query: 'urgency:1', country: 'fra' })
// Update a filter
await fc.update('breaking-politics', { query: 'urgency:1 OR urgency:2' })
// Get a specific filter
const filter = await fc.get('breaking-politics')
// List all filters
const allFilters = await fc.all()
// Delete a filter
await fc.delete('breaking-politics')Search with Saved Filter
const { count, documents } = await afp.searchWithFilter('my-filter', {
startat: 0,
size: 50
})
// Parsed into AfpDocument
const { documents } = await afp.searchWithFilter('my-filter', { startat: 0, size: 50 }, { parse: true })RSS/ATOM Feed
Retrieve an RSS/ATOM feed based on a saved filter:
const xmlContent = await afp.feed('my-filter', { size: 20 })Notification Center
Subscribe to real-time document notifications via mail, REST, SQS, or JMS services.
const nc = afp.notificationCenter
// Register a REST service
const serviceId = await nc.registerService({
name: 'my-webhook',
type: 'rest',
datas: { href: 'https://example.com/webhook' }
})
// Add a subscription
const subId = await nc.addSubscription('breaking-news', 'my-webhook', {
query: 'urgency:1',
langs: ['en']
})
// List services and subscriptions
const services = await nc.listServices()
const subscriptions = await nc.listSubscriptions()
const subs = await nc.subscriptionsInService('my-webhook')
// Cleanup
await nc.deleteSubscription('my-webhook', 'breaking-news')
await nc.removeSubscriptionsFromService('my-webhook', ['sub1', 'sub2'])
await nc.deleteService('my-webhook')Social Stories
Retrieve the embeddable HTML for a social story document:
const html = afp.getStoryHtml(doc)Search Parameters Reference
| Parameter | Type | Default | Description |
|---|---|---|---|
| query | string | — | Boolean query string (see Query Syntax) |
| langs | string[] | — | Filter by language codes |
| dateFrom | string | '1980-01-01' | Start date (ISO date or relative like 'now-7d') |
| dateTo | string | 'now' | End date |
| size | number | 10 | Number of results (max 10000 per request) |
| sortField | string | 'published' | Field to sort by |
| sortOrder | 'asc' \| 'desc' | 'desc' | Sort direction |
| startAt | number | — | Offset for pagination |
| tz | string | — | Timezone (e.g. 'Europe/Paris') |
| dateGap | string | — | Date gap for facet ranges (e.g. '+1HOUR', '+1DAY') |
| wantedFacets | WantedFacets | — | Facets configuration { facetName: { size, minDocCount }, empty?: boolean } |
| sort | SortEntry[] | — | Multi-field sort [{ sortField, sortOrder }] |
| filters | SearchFilters | — | Field filters { field: value \| value[] \| { in, exclude, and, contains, range, exists } } (see Field Filters) |
| dateField | string | 'published' (API) | Date field dateFrom / dateTo apply to (dateRange.targetField) |
| exactNumFound | boolean \| number | — | Total count: exact, none, or bounded |
Any other key-value pair is still read as a field filter, but this is deprecated (removed in 4.0): use filters.
Development
# Install dependencies
npm install
# Build (clean + parser + types + ESM/CJS/bundles)
npm run build
# Development with auto-rebuild
npm run build:watch
# Run tests
npm test
# Run tests in watch mode
npm run test:watch
# Lint
npm run lintAuthor
License
MIT - see LICENSE.md
