# finlight API Documentation — Full Content > Complete documentation for the finlight financial news API (REST, WebSocket, > Webhooks, and MCP server), concatenated as plain markdown for LLM consumption. > A shorter, link-based index is available at https://docs.finlight.me/llms.txt > Every page is also available on its own — append `.md` to its URL, e.g. > https://docs.finlight.me/en/v2/rest-basics.md # Quickstart URL: https://docs.finlight.me/en/v2/ The **finlight.me API** is a real-time financial news API that provides market-relevant news articles enriched with sentiment analysis. It offers both REST and WebSocket APIs, allowing developers to access and integrate financial news data into their applications efficiently. - **Real-time Financial News**: Stay updated with the latest financial news articles as they are published. - **Sentiment Analysis**: Each article includes sentiment data, helping you gauge market sentiment quickly. Get started quickly with the finlight.me API by following these simple steps: ## Sign Up and Get Your Free API Key - Visit the [finlight Dashboard](https://app.finlight.me) and sign up for a free account. - Once registered, navigate to the **API Keys** section to obtain your API key. - The free tier includes **5,000 requests per month** for more details visit the [pricing section](https://finlight.me/pricing). ## Choose your client Before making your first API request, you need to pick which API client you will use. In addition to good ol' cURL HTTP requests, finlight offers official client libraries for eight languages — see [Client Libraries](https://docs.finlight.me/en/v2/client-libraries/) for the full list. In the following example, you can see how to install each client. **cURL:** ```bash # cURL is most likely already installed on your machine curl --version ``` **TypeScript:** ```bash # Install the Node.js client library via npm npm install finlight-client ``` **Python:** ```bash # Install the Python client library via pip pip install finlight-client ``` **Go:** ```bash go get github.com/callbk/finlight-client-go ``` **C#:** ```bash dotnet add package Finlight.Client ``` **Java:** ```kotlin // build.gradle.kts dependencies { implementation("me.finlight:finlight-client:0.1.0") } ``` **PHP:** ```bash composer require finlight/client ``` **Ruby:** ```bash gem install finlight-client ``` **Rust:** ```bash cargo add finlight-client tokio futures-util ``` ## Make Your First API Call After picking your preferred client, you are ready to make your first call to the finlight API. Below, you can see how to send a POST request to the Articles endpoint to search for articles with the example query. **(POST /v2/articles):** **cURL:** ```bash curl -X POST 'https://api.finlight.me/v2/articles' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -H 'X-API-KEY: YOUR_API_KEY' \ -d '{ "query": "Nvidia" }' ``` ```typescript const api = new FinlightApi({ apiKey: 'YOUR_API_KEY' }) // Replace with your API key api.articles .fetchArticles({ query: "Nvidia", language: "en" }) .then((articles) => console.log(articles)) .catch((error) => console.error(error)) ``` ```python from finlight_client import FinlightApi, ApiConfig from finlight_client.models import GetArticlesParams def main(): client = FinlightApi( config=ApiConfig( api_key="YOUR_API_KEY" ) ) params = GetArticlesParams(query="Nvidia", language="en") articles = client.articles.fetch_articles(params=params) if __name__ == "__main__": main() ``` ```go client, err := finlight.New(finlight.Config{APIKey: "YOUR_API_KEY"}) if err != nil { log.Fatal(err) } response, err := client.Articles.FetchArticles(context.Background(), finlight.GetArticlesParams{ Query: "Nvidia", Language: "en", }) if err != nil { log.Fatal(err) } for _, article := range response.Articles { fmt.Println(article.Title) } ``` ```csharp using Finlight; using var client = new FinlightClient("YOUR_API_KEY"); var response = await client.Articles.FetchArticlesAsync(new GetArticlesParams { Query = "Nvidia", Language = "en", }); foreach (var article in response.Articles) { Console.WriteLine(article.Title); } ``` ```java FinlightClient client = FinlightClient.create("YOUR_API_KEY"); ArticleResponse response = client.articles().fetchArticles( GetArticlesParams.builder() .query("Nvidia") .language("en") .build()); response.articles().forEach(article -> System.out.println(article.title())); ``` ```php use Finlight\FinlightClient; use Finlight\Request\GetArticlesParams; $client = new FinlightClient('YOUR_API_KEY'); $response = $client->articles->fetchArticles(new GetArticlesParams( query: 'Nvidia', language: 'en', )); foreach ($response as $article) { echo $article->title, PHP_EOL; } ``` ```ruby require "finlight/client" client = Finlight::Client.new(api_key: "YOUR_API_KEY") response = client.articles.fetch_articles(query: "Nvidia", language: "en") response.articles.each { |article| puts article.title } ``` ```rust use finlight_client::{Client, Config, GetArticlesParams}; let client = Client::new(Config::new("YOUR_API_KEY"))?; let response = client .articles .fetch_articles(&GetArticlesParams { query: Some("Nvidia".into()), language: Some("en".into()), ..Default::default() }) .await?; for article in response.articles { println!("{}", article.title); } ``` ## What's next? Great, you're now set up with an API client and have made your first request to the API. Here are a few links that might be handy as you venture further into the finlight API: - [Check out the REST API endpoints](https://docs.finlight.me/en/v2/rest-endpoints) - [Check out the WebSocket section](https://docs.finlight.me/en/v2/websocket-quickstart) --- # Basics URL: https://docs.finlight.me/en/v2/rest-basics/ ## Endpoint Structure All REST API endpoints are accessed via the base URL: ``` https://api.finlight.me ``` Endpoints are structured using standard HTTP methods and expect parameters to be sent as query strings. ## API Versioning The REST API is versioned to ensure backward compatibility. The current version is `v2`. All endpoints include the version number in the URL: ``` https://api.finlight.me/v2/... ``` This allows for future updates without breaking existing integrations. ## Authentication Headers Authenticate your REST API requests by including your API key in the `X-API-KEY` header: ``` X-API-KEY: YOUR_API_KEY ``` > **Note:** > If you're using our client libraries, this header is automatically handled for > you. You can grab your API key in the [finlight Dashboard](https://app.finlight.me). --- # Endpoints URL: https://docs.finlight.me/en/v2/rest-endpoints/ On this page, we'll dive into the different endpoints you can use to retrieve financial news articles programmatically. We'll look at how to query articles using the finlight.me API. --- ## Article model The response article model contains all the information about an article, such as the link, title, publish date and source. It also contains a sentiment and its confidence about that. - `link` (string): URL to the full article. - `source` (string): Source website. E.g. `www.reuters.com` - `title` (string): Title of the article. - `summary` (string): Summary of the article if existing. Can be nullable. - `publishDate` (Date): Publication date as ISO date. - `createdAt` (Date): Date the article was first indexed by the finlight system, as ISO 8601 date string. Returned only when `orderBy=createdAt` is used. - `revisedDate` (Date | null): Date the article was last revised after initial publication, as ISO 8601 date string. `null` when the article has never been revised. Returned when `orderBy=revisedDate` is used or `includeUpdates` is enabled via WebSocket/Webhook. - `isUpdate` (boolean): `true` when this article payload is a re-delivery triggered by a post-publication revision. Only present when `includeUpdates` is enabled on a WebSocket or Webhook subscription. - `language` (string): Language code in [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1). E.g. `en` | `de` | `fr` - `sentiment` (string): Sentiment analysis result. Values can be `positive` | `neutral` |`negative` - `confidence` (string): Confidence level of sentiment analysis from 0 to 1, returned as a stringified number (e.g. `"0.95"`). The TypeScript and Python clients parse it to a number for you. - `images` (string[]): Array of image URLs from the article. - `countries` (string[]): Array of country codes in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format representing the countries related to the article. E.g. `["US", "GB", "DE"]`. Can be empty. - `categories` (string[]): Array of article categories. Possible values: `markets` | `economy` | `business` | `politics` | `geopolitics` | `regulation` | `technology` | `energy` | `commodities` | `crypto` | `health` | `climate` | `security`. Can be empty. - `companies` (Company[]): Array of companies that are mentioned in the article. Is only shown/available with [specific subscription tier](https://finlight.me/pricing). Can be nullable. ## Company model The response company model contains information about a company that is mentioned in an article. It includes details like the company name, ticker symbol, industry, and more. - `companyId` (number): Unique identifier for the company. - `confidence` (string): Confidence level of the company identification, as a stringified number between 0 and 1 (e.g. `"0.93"`). The TypeScript and Python clients parse it to a number for you. - `country` (string): Country where the company is based in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. E.g. `US` | `DE` | `GB` - `exchange` (string): Stock exchange where the company is listed. - `industry` (string): Industry sector of the company. E.g. `Biotechnology, Technology` - `name` (string): Full name of the company. E.g. `Apple Inc.` - `sector` (string): Sector of the company. E.g. `Technology` | `Health Care` - `ticker` (string): Stock ticker symbol of the company. E.g. `AAPL` | `GOOGL` - `isin` (string): International Securities Identification Number (ISIN) of the company. E.g. `US0378331005` - `openfigi` (string): OpenFIGI identifier for the company. E.g. `BBG000B9XRY4` - `primaryListing` (object): Primary stock exchange listing information for the company. - `primaryListing.ticker` (string): Primary ticker symbol on the main exchange. - `primaryListing.exchangeCode` (string): Code of the primary exchange where the stock is listed. - `primaryListing.exchangeCountry` (string): Country of the primary exchange where the stock is listed. - `isins` (string[]): Array of International Securities Identification Numbers (ISINs) for the company. - `otherListings` (object[]): Array of other stock exchange listings for the company. - `otherListings[].ticker` (string): Ticker symbol on the alternative exchange. - `otherListings[].exchangeCode` (string): Code of the alternative exchange where the stock is listed. - `otherListings[].exchangeCountry` (string): Country of the alternative exchange where the stock is listed. --- ## Fetch articles (POST /v2/articles) Retrieve **article information**, including detailed analysis, companies and more. Please note that some fields require a specific subscription tier to access. ### Optional BODY parameters Because this endpoint uses a POST request, you can pass parameters in the body of the request. This allows for more complex queries and filtering options. - `query` (string): Search query to find relevant articles with simple or advanced filters. [Advanced queries](https://docs.finlight.me/v2/advanced-query-building/) - `sources` (string[]): Simple filter for single or multiple sources (String Array). See "Get all sources" endpoint for valid values. **Supports wildcard `"*"`** to include all sources. - `optInSources` (string[]): Additional sources to include on top of your default source set (String Array). See "Get all sources" endpoint for valid values. - `excludeSources` (string[]): Excludes single or multiple sources (String Array). See "Get all sources" endpoint for valid values. - `tickers` (string[]): Filter by stock ticker symbols (String Array). This will return articles that mention these tickers. **Supports wildcard `"*"`** to include all tickers. - `countries` (string[]): Filter by the countries an article is about, using [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country codes (String Array). E.g. `["US", "GB", "DE"]`. This matches the article's `countries` field, not the publisher's country, a company's domicile, or a listing market. - `categories` (string[]): Filter by article category (String Array). Possible values: `markets`, `economy`, `business`, `politics`, `geopolitics`, `regulation`, `technology`, `energy`, `commodities`, `crypto`, `health`, `climate`, `security`. - `includeEntities` (boolean, default: false): Includes the companies mentioned in the article. Requires a specific subscription tier. - `from` (string): Start date in `YYYY-MM-DD` format or ISO date string. - `to` (string): End date in `YYYY-MM-DD` format or ISO date string. - `language` (string, default: en): Filter by language ([ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1)). **Defaults to `en`, which returns English only and excludes other languages** — see [Language & Coverage](https://docs.finlight.me/en/v2/advanced-query-building/#language-and-multilingual-coverage). - `orderBy` (string): Order by (`"publishDate"`, `"createdAt"`, or `"revisedDate"`) - default `"publishDate"`. `publishDate` is the article's publication date from the source. `createdAt` is when the article was first indexed by finlight. `revisedDate` sorts by the most recent revision date (articles never revised appear last). Keep in mind that some sources publish articles with past publication dates. - `order` (string): Sort order (`"ASC"` or `"DESC"`) - default `"DESC"`. - `pageSize` (number, default: 20): Number of results per page (1-100). - `page` (number, default: 1): Page number. **Request (POST /v2/articles):** **cURL:** ```bash curl -X POST 'https://api.finlight.me/v2/articles' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -H 'X-API-KEY: YOUR_API_KEY' \ -d '{ "query": "Nvidia", "countries": ["US", "GB"] }' ``` ```typescript import { FinlightApi } from "finlight-client"; const api = new FinlightApi({ apiKey: 'YOUR_API_KEY' }) api.articles .fetchArticles({ query: 'Nvidia', countries: ['US', 'GB'] }) .then((articles) => console.log(articles)) .catch((error) => console.error(error)) ``` ```python from finlight_client import FinlightApi, ApiConfig from finlight_client.models import GetArticlesParams client = FinlightApi( config=ApiConfig( api_key="your_api_key" ) ) params = GetArticlesParams( query="Nvidia", countries=["US", "GB"] ) response = client.articles.fetch_articles(params=params) print(response) ``` ```go client, err := finlight.New(finlight.Config{APIKey: "YOUR_API_KEY"}) if err != nil { log.Fatal(err) } response, err := client.Articles.FetchArticles(context.Background(), finlight.GetArticlesParams{ Query: "Nvidia", Countries: []string{"US", "GB"}, }) if err != nil { log.Fatal(err) } for _, article := range response.Articles { fmt.Println(article.Title) } ``` ```csharp using Finlight; using var client = new FinlightClient("YOUR_API_KEY"); var response = await client.Articles.FetchArticlesAsync(new GetArticlesParams { Query = "Nvidia", Countries = new[] { "US", "GB" }, }); foreach (var article in response.Articles) { Console.WriteLine(article.Title); } ``` ```java FinlightClient client = FinlightClient.create("YOUR_API_KEY"); ArticleResponse response = client.articles().fetchArticles( GetArticlesParams.builder() .query("Nvidia") .countries(List.of("US", "GB")) .build()); response.articles().forEach(article -> System.out.println(article.title())); ``` ```php use Finlight\FinlightClient; use Finlight\Request\GetArticlesParams; $client = new FinlightClient('YOUR_API_KEY'); $response = $client->articles->fetchArticles(new GetArticlesParams( query: 'Nvidia', countries: ['US', 'GB'], )); foreach ($response as $article) { echo $article->title, PHP_EOL; } ``` ```ruby require "finlight/client" client = Finlight::Client.new(api_key: "YOUR_API_KEY") response = client.articles.fetch_articles(query: "Nvidia", countries: %w[US GB]) response.articles.each { |article| puts article.title } ``` ```rust use finlight_client::{Client, Config, GetArticlesParams}; let client = Client::new(Config::new("YOUR_API_KEY"))?; let response = client .articles .fetch_articles(&GetArticlesParams { query: Some("Nvidia".into()), countries: Some(vec!["US".into(), "GB".into()]), ..Default::default() }) .await?; for article in response.articles { println!("{}", article.title); } ``` **Response:** ```json { "status": "ok", "page": 1, "pageSize": 20, "articles": [ { "link": "https://www.example.com/article1", "source": "www.example.com", "title": "Stock Market Hits New Highs", "summary": "A brief summary of the article...", "publishDate": "2023-10-01T12:34:56Z", "language": "en", "sentiment": "positive", "confidence": "0.95", "images": [ "https://www.example.com/image1.jpg", "https://www.example.com/image2.jpg" ], "countries": ["US"], "categories": ["markets", "technology"], "companies": [ { "companyId": 41494, "confidence": "0.9335401058197021", "country": "US", "exchange": "XNAS", "industry": "Biotechnology: Pharmaceutical Preparations", "name": "Summit Therapeutics Inc. Common Stock", "sector": "Health Care", "ticker": "SMMT", "isin": "US86627T1088", "openfigi": "BBG01PH11VP5", "primaryListing": { "ticker": "SMMT", "exchangeCode": "XNAS", "exchangeCountry": "US" }, "isins": ["US86627T1088", "US86627T2088"], "otherListings": [ { "ticker": "SMMT.L", "exchangeCode": "XLON", "exchangeCountry": "GB" } ] }, ... ] }, // ... ] } ``` --- ## Fetch article by link (GET /v2/articles/by-link) Retrieve a **single article** by its URL. Returns the full article data with sentiment analysis and optionally includes content and company entities. ### Required query parameters - `link` (string): The URL of the article to fetch. ### Optional query parameters - `includeContent` (boolean, default: false): **(Deprecated)** Include the full article content in the response. - `includeEntities` (boolean, default: false): Include the companies mentioned in the article. Requires a specific subscription tier. **Request (GET /v2/articles/by-link):** **cURL:** ```bash curl -X GET 'https://api.finlight.me/v2/articles/by-link?link=https%3A%2F%2Fwww.somepage.com%2Ftechnology%2Fexample-article&includeContent=true&includeEntities=true' \ -H 'accept: application/json' \ -H 'X-API-KEY: YOUR_API_KEY' ``` ```typescript import { FinlightApi } from "finlight-client"; const api = new FinlightApi({ apiKey: 'YOUR_API_KEY' }); const article = await api.articles .fetchArticleByLink({ link: 'https://www.somepage.com/technology/example-article', includeContent: true, includeEntities: true, }); console.log(article); ``` ```python from finlight_client import FinlightApi, ApiConfig from finlight_client.models import GetArticleByLinkParams client = FinlightApi( config=ApiConfig( api_key="YOUR_API_KEY" ) ) params = GetArticleByLinkParams( link="https://www.somepage.com/technology/example-article", includeContent=True, includeEntities=True, ) article = client.articles.fetch_article_by_link(params=params) print(article) ``` ```go article, err := client.Articles.FetchArticleByLink(context.Background(), finlight.GetArticleByLinkParams{ Link: "https://www.somepage.com/technology/example-article", IncludeContent: true, IncludeEntities: true, }) if err != nil { log.Fatal(err) } fmt.Println(article.Title) ``` ```csharp var article = await client.Articles.FetchArticleByLinkAsync(new GetArticleByLinkParams { Link = "https://www.somepage.com/technology/example-article", IncludeContent = true, IncludeEntities = true, }); Console.WriteLine(article.Title); ``` ```java // The link is required, so it is passed to the builder factory. Article article = client.articles().fetchArticleByLink( GetArticleByLinkParams.builder("https://www.somepage.com/technology/example-article") .includeContent(true) .includeEntities(true) .build()); System.out.println(article.title()); ``` ```php use Finlight\Request\GetArticleByLinkParams; $article = $client->articles->fetchArticleByLink(new GetArticleByLinkParams( link: 'https://www.somepage.com/technology/example-article', includeContent: true, includeEntities: true, )); echo $article->title, PHP_EOL; ``` ```ruby article = client.articles.fetch_article_by_link( link: "https://www.somepage.com/technology/example-article", include_content: true, include_entities: true ) puts article.title ``` ```rust use finlight_client::GetArticleByLinkParams; let article = client .articles .fetch_article_by_link(&GetArticleByLinkParams { link: "https://www.somepage.com/technology/example-article".into(), include_content: true, include_entities: true, }) .await?; println!("{}", article.title); ``` **Response:** ```json { "status": "ok", "article": { "link": "https://www.somepage.com/technology/example-article", "source": "www.reuters.com", "title": "Nvidia Announces New GPU Architecture", "summary": "A brief summary of the article...", "publishDate": "2023-10-01T12:34:56Z", "language": "en", "sentiment": "positive", "confidence": "0.95", "content": "Full article content here...", "images": [ "https://www.example.com/image1.jpg" ], "countries": ["US"], "categories": ["technology"], "companies": [ { "companyId": 4157, "confidence": "0.97", "country": "US", "exchange": "XNAS", "industry": "Semiconductors", "name": "NVIDIA Corporation", "sector": "Technology", "ticker": "NVDA", "isin": "US67066G1040", "openfigi": "BBG000BBJQV0" } ] } } ``` --- ## Get all sources (GET /v2/sources) Retrieve a list of all currently supported article sources. > **Note:** The sources are scraped on a best-effort basis and may change in the future. ### Response A JSON array of source objects. Example: - `array` (Source[]): Array of news sources. ### Source model The response source model contains information about a news source, including its domain, origin country, languages, and whether it is a default source. - `domain` (string): Domain of the source website. - `isDefaultSource` (boolean): Indicates if this source is served by default (without having to include it in `sources`). - `originCountry` (string): Origin country of the source in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. E.g. `US` | `GB` | `DE`. Can be empty. - `languages` (string[]): Languages the source publishes in, as [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1) codes, primary (most-common) first. E.g. `["en"]`. - `isCustomSource` (boolean): Present and `true` only when this source is a custom source enabled for your subscription. - `isContentAvailable` (boolean): **(Deprecated)** Whether scraped content is available for this source. Only present on plans with full article content access. **Request (GET /v2/sources):** **cURL:** ```bash curl -X GET 'https://api.finlight.me/v2/sources' \ -H 'X-API-KEY: YOUR_API_KEY' ``` ```typescript client.sources .getSources() .then((sources) => console.log(sources)); ``` ```python sources = client.sources.get_sources() print(sources) ``` ```go sources, err := client.Sources.GetSources(context.Background()) if err != nil { log.Fatal(err) } fmt.Println(sources) ``` ```csharp var sources = await client.Sources.GetSourcesAsync(); Console.WriteLine(sources.Count); ``` ```java List sources = client.sources().getSources(); sources.forEach(source -> System.out.println(source.domain())); ``` ```php $sources = $client->sources->getSources(); foreach ($sources as $source) { echo $source->domain, PHP_EOL; } ``` ```ruby sources = client.sources.get_sources sources.each { |source| puts source.domain } ``` ```rust let sources = client.sources.get_sources().await?; for source in sources { println!("{}", source.domain); } ``` **Response:** ```json [ { "domain": "www.yahoo.com", "isDefaultSource": true, "originCountry": "US", "languages": ["en"] }, { "domain": "seekingalpha.com", "isDefaultSource": true, "originCountry": "US", "languages": ["en"] }, // ... ] ``` --- # Errors & Status Codes URL: https://docs.finlight.me/en/v2/errors/ The finlight API uses conventional HTTP status codes to signal the outcome of a request. A `2xx` status means success; `4xx` means the request was rejected (usually something you can fix); `5xx` means a problem on our side. Every error returns a JSON body describing what went wrong. > **Note:** REST and WebSocket requests authenticate with the `X-API-KEY` header. A missing or invalid key returns `401`. (Webhook *delivery* auth — the headers finlight sends to **your** endpoint — is separate; see [Webhook Authentication](https://docs.finlight.me/en/v2/webhooks/authentication/).) ## Status codes at a glance | Status | Meaning | When it happens | | --- | --- | --- | | `200` | OK | Successful request. | | `400` | Bad Request | Invalid parameters or malformed query syntax. | | `401` | Unauthorized | Missing or invalid `X-API-KEY`. | | `403` | Forbidden | Your plan doesn't include the requested capability. | | `404` | Not Found | The requested resource doesn't exist (e.g. unknown article link). | | `422` | Unprocessable Entity | Request body/params failed validation (global validator). | | `429` | Too Many Requests | Monthly quota or burst rate limit exceeded. | | `500` | Internal Server Error | Unexpected error on finlight's side. | --- ## 400 — Bad Request Returned when query parameters or the request body fail validation, or when the `query` string uses invalid field-level syntax. **Invalid parameter:** ```json { "statusCode": 400, "message": ["pageSize must not be greater than 100"], "error": "Bad Request" } ``` **Invalid `query` syntax (POST `/v2/articles`):** ```json { "statusCode": 400, "message": [ { "property": "query", "constraints": { "query": "Invalid query syntax near 'ticker:'" } } ], "error": "Bad Request" } ``` See [Advanced Query Building](https://docs.finlight.me/en/v2/advanced-query-building/) for the correct `query` syntax. --- ## 401 — Unauthorized The `X-API-KEY` header is missing, malformed, or not a valid key. ```json { "statusCode": 401, "message": "Unauthorized" } ``` Grab or rotate your key in the [finlight dashboard](https://app.finlight.me). --- ## 403 — Forbidden The request is authenticated, but your **plan** doesn't include the requested capability — for example, requesting full article content on a plan that doesn't include it. ```json { "statusCode": 403, "message": "Your subscription does not allow calling the extended article content" } ``` See [Rate Limits & Quotas](https://docs.finlight.me/en/v2/rate-limits/) for which capabilities each plan includes. --- ## 404 — Not Found The requested resource doesn't exist — most commonly `GET /v2/articles/by-link` with a `link` finlight hasn't indexed. ```json { "statusCode": 404, "message": "Article not found" } ``` --- ## 422 — Unprocessable Entity Some endpoints validate through the global validator, which returns a field-keyed error map. Each key is the offending field; the value lists the failed constraints. ```json { "status": 422, "errors": { "language": "language must be a string" } } ``` > **Note:** Validation failures may surface as `400` (on the article endpoints) or `422` (global validator), depending on the route — both indicate a malformed request. Inspect the body to see which field failed. --- ## 429 — Too Many Requests You've exceeded a usage limit. There are two distinct cases, each with a specific message: **Monthly request quota exceeded:** ```json { "statusCode": 429, "message": "Throttling Exception: Exceeded token limit of 5000 for the current period." } ``` **Burst (short-term) rate exceeded:** ```json { "statusCode": 429, "message": "Throttling Exception: Exceeded rate limit of 10 requests per 10 seconds." } ``` > **Note:** finlight does **not** currently return `Retry-After` or rate-limit headers. For a **burst** `429`, back off and retry after ~10 seconds. For a **monthly quota** `429`, requests will succeed again at the start of your next billing period (or after an upgrade). See [Rate Limits & Quotas](https://docs.finlight.me/en/v2/rate-limits/). --- ## 500 — Internal Server Error An unexpected error occurred on finlight's side. These are transient — retry with backoff, and if it persists, reach out via [Support](https://docs.finlight.me/en/v2/support/). ```json { "statusCode": 500, "message": "Internal server error" } ``` --- ## Handling errors well - **Always check the status code first**, then read the JSON body for specifics. - **`4xx` (except `429`) are your bug** — fix the request; retrying unchanged won't help. - **`429` and `5xx` are retryable** — use exponential backoff. For burst `429`, ~10s is enough. - **WebSocket** errors arrive as an `error` server message on the socket rather than an HTTP status — see [WebSocket Basics](https://docs.finlight.me/en/v2/websocket-basics/). - **Webhook** delivery failures (to your endpoint) are tracked in the dashboard, not returned to you synchronously — see [Testing Webhooks](https://docs.finlight.me/en/v2/webhooks/testing/). --- # Rate Limits & Quotas URL: https://docs.finlight.me/en/v2/rate-limits/ Every finlight API key is bound to a **plan**, and the plan defines your usage limits and which capabilities you can access. Limits are enforced per API key, in real time. This page explains each limit and what each plan unlocks; for the exact numbers on your plan, see the [finlight dashboard](https://app.finlight.me) or the [pricing page](https://finlight.me). --- ## The four usage limits - `Monthly request quota`: Each REST request consumes **one** request from your monthly allowance. The counter resets at the start of every billing period. Exceeding it returns [`429`](https://docs.finlight.me/en/v2/errors/#429-too-many-requests) with *"Exceeded token limit of N for the current period."* - `Burst rate`: A short-term limit on requests per **10 seconds**, smoothing spikes. Only enforced on plans that define it. Exceeding it returns [`429`](https://docs.finlight.me/en/v2/errors/#429-too-many-requests) with *"Exceeded rate limit of N requests per 10 seconds."* — back off ~10s and retry. - `WebSocket connections`: The maximum number of **concurrent** WebSocket connections for your key. New connections beyond the limit are rejected. A separate cap limits the total number of streamed messages per period. WebSocket requires a paid plan. - `Webhook delivery quota`: The maximum number of webhook **deliveries** per billing period. A companion limit caps how many webhooks you can create. When the delivery quota is exhausted, deliveries pause until the next period. --- ## Capabilities unlocked by your plan Beyond raw limits, your plan controls which **features** are available. Requesting a feature your plan doesn't include returns [`403`](https://docs.finlight.me/en/v2/errors/#403-forbidden) (for REST) or simply omits the data (for webhooks/WebSocket). - `Historical data`: How far back you can query depends on your plan. The Free and Pro Light plans currently cover roughly the **last month** of articles; higher plans unlock deeper historical coverage. Use the `from` / `to` date filters to query within your plan's window — requests for dates outside it simply return no results for that range. See the [pricing page](https://finlight.me) for each plan's exact history window. - `Sentiment analysis`: Includes the `sentiment` and `confidence` fields on articles. Stripped from payloads when not granted. - `Company entities`: Includes the `companies` array (AI-resolved tickers, ISIN, exchange, etc.) and enables `includeEntities`. Stripped when not granted. - `Custom sources`: Private or customer-specific news sources added to your default set. Available on higher / enterprise plans. --- ## How enforcement works - **Per key, in real time.** Each request increments your counters; once a limit is crossed the API returns `429` immediately. - **Dashboard usage isn't live.** The usage shown in the [finlight dashboard](https://app.finlight.me) is aggregated about **once a day** and reflects activity **through the previous day** — it is not a real-time counter. Enforcement is live, so your actual remaining quota for *today* can differ from what the dashboard shows. - **Monthly counters reset** at the start of your billing period — a quota `429` clears automatically. - **No rate-limit headers.** finlight does not currently send `Retry-After` or `X-RateLimit-*` headers. Treat a burst `429` as "wait ~10 seconds"; treat a monthly `429` as "quota reached for this period." See [Errors & Status Codes](https://docs.finlight.me/en/v2/errors/). --- ## Plans | Plan | Typical use | | --- | --- | | **Free** | Evaluation and low-volume use. REST only (no WebSocket). | | **Pro (Light / Standard / Scale)** | Production workloads with increasing quotas, WebSocket, webhooks, and richer enrichment. | | **Enterprise** | High volume, custom sources, and bespoke limits. | > **Note:** > Exact numeric limits (monthly tokens, burst rate, WebSocket connections, webhook quota) and the feature set per plan are part of pricing and can change. Always check your **current** plan's limits in the [finlight dashboard](https://app.finlight.me), or compare plans on the [pricing page](https://finlight.me). Need higher limits or custom sources? [Contact us](https://docs.finlight.me/en/v2/support/). --- ## When you hit a limit - **Burst `429`** → pause ~10 seconds, then continue. - **Monthly quota `429`** → you've used your period's requests; upgrade, or wait for the reset. - **WebSocket connection rejected** → you're at your concurrent-connection cap; close an idle connection (see the `takeover` option in [WebSocket Quickstart](https://docs.finlight.me/en/v2/websocket-quickstart/)). - **Webhook deliveries paused** → your delivery quota for the period is exhausted; it resumes next period. - **`403` on a feature** → that capability isn't in your plan; see the table above. For the exact error bodies, see [Errors & Status Codes](https://docs.finlight.me/en/v2/errors/). --- # Quickstart URL: https://docs.finlight.me/en/v2/websocket-quickstart/ The **finlight.me WebSocket API** allows you to receive real-time financial news articles as they are published. Unlike the REST API, which requires periodic polling to fetch new data, the WebSocket API pushes newly published articles to you in real-time, ensuring you stay updated without making repeated requests. - **Real-time Updates**: Once connected, you first receive the latest matching article for your query. After that, any newly published articles that match your query are sent to you automatically. - **Continuous Streaming**: Stay connected as long as needed. Each pricing tier includes a fixed number of parallel WebSocket connections that can remain open throughout the month. There is no usage-based pricing — you’re only limited by the number of concurrent connections allowed in your tier. - **Sentiment Analysis**: Articles come with sentiment data to help you quickly assess market mood. ## Sign Up and Get Your Free API Key If you haven’t already, sign up at the [finlight Dashboard](https://app.finlight.me) to obtain your free API key. This key will be used to authenticate your WebSocket connection, just like with the REST API. ## Choose Your Client To connect to the finlight.me WebSocket API, you can use any of our client libraries with streaming support. These libraries simplify handling the connection, authentication, and keep-alive mechanisms (ping/pong). The PHP client is the one exception — it has no WebSocket support, so use [webhooks](https://docs.finlight.me/en/v2/webhooks/) for push delivery into a PHP application. **TypeScript:** ```bash # Install the Node.js client library via npm npm install finlight-client ``` **Python:** ```bash # Install the Python client library via pip pip install finlight-client ``` **Go:** ```bash go get github.com/callbk/finlight-client-go ``` **C#:** ```bash dotnet add package Finlight.Client ``` **Java:** ```kotlin // build.gradle.kts dependencies { implementation("me.finlight:finlight-client:0.1.0") } ``` **Ruby:** ```bash gem install finlight-client ``` **Rust:** ```bash cargo add finlight-client tokio futures-util ``` ## Connect and Receive Real-Time Articles With your API key and chosen client, you can now establish a WebSocket connection. Upon connecting, you'll immediately receive the most recent article matching your query, followed by any new articles as they come in. The client libraries handle authentication and the ping/pong keep-alive mechanism for you. **(WebSocket wss://wss.finlight.me):** ```typescript const client = new FinlightApi({ apiKey: 'YOUR_API_KEY', }) client.websocket.connect( { query: 'nvidia', language: 'en' }, (article) => { console.log('New article received:', article) }, ) ``` ```python from finlight_client import FinlightApi, ApiConfig from finlight_client.models import GetArticlesWebSocketParams def on_article(data): print(data) async def main(): client = FinlightApi( config=ApiConfig( api_key="YOUR_API_KEY" ) ) payload = GetArticlesWebSocketParams(query="nvidia", extended=False) await client.websocket.connect(request_payload=payload, on_article=on_article) if __name__ == "__main__": asyncio.run(main()) ``` ```go // Streams are Go iterators: range over them, break to stop, // cancel the context to shut down. client, err := finlight.New(finlight.Config{APIKey: "YOUR_API_KEY"}) if err != nil { log.Fatal(err) } for article := range client.Websocket.Stream(ctx, finlight.GetArticlesWebSocketParams{ Query: "nvidia", Language: "en", }) { fmt.Println("New article received:", article.Title) } if err := client.Websocket.Err(); err != nil { log.Fatal(err) } ``` ```csharp using Finlight; using var client = new FinlightClient("YOUR_API_KEY"); await foreach (var article in client.WebSocket.StreamAsync(new GetArticlesWebSocketParams { Query = "nvidia", Language = "en", }, cancellationToken)) { Console.WriteLine($"New article received: {article.Title}"); } ``` ```java FinlightClient client = FinlightClient.create("YOUR_API_KEY"); // connect blocks and reconnects automatically; use connectAsync for a background thread. client.webSocket().connect( GetArticlesWebSocketParams.builder() .query("nvidia") .language("en") .build(), article -> System.out.println("New article received: " + article.title())); ``` ```ruby require "finlight/client" client = Finlight::Client.new(api_key: "YOUR_API_KEY") client.websocket.connect(query: "nvidia", language: "en") do |article| puts "New article received: #{article.title}" end ``` ```rust use finlight_client::{Client, Config, GetArticlesWebSocketParams}; use futures_util::StreamExt; let client = Client::new(Config::new("YOUR_API_KEY"))?; let mut stream = client.websocket.stream(GetArticlesWebSocketParams { query: Some("nvidia".into()), language: Some("en".into()), ..Default::default() }); while let Some(item) = stream.next().await { let article = item?; println!("New article received: {}", article.title); } ``` This connection remains open as long as you need it, continually delivering new articles that match your query. Remember that your billing is based on connection duration, so be mindful to disconnect when you no longer need updates. ### Managing Connection Limits Each pricing tier includes a fixed number of parallel WebSocket connections. If you reach your limit and try to open another connection, you can enable the **takeover** option to automatically close the oldest connection: In TypeScript, Python, Java and Ruby the option is set on the client you already have. In Go, C# and Rust the top-level client always uses the default stream options, so takeover is configured on a directly constructed stream client instead. ```typescript const client = new FinlightApi( { apiKey: 'YOUR_API_KEY', }, { // WebSocket-specific options takeover: true, // Automatically close oldest connection when limit is reached (default: false) }, ) client.websocket.connect( { query: 'nvidia', language: 'en' }, (article) => { console.log('New article received:', article) }, ) ``` ```python from finlight_client import FinlightApi, ApiConfig, WebSocketOptions from finlight_client.models import GetArticlesWebSocketParams def on_article(data): print(data) async def main(): client = FinlightApi( config=ApiConfig( api_key="YOUR_API_KEY" ), websocket_options=WebSocketOptions( takeover=True # Automatically close oldest connection when limit is reached (default: False) ) ) payload = GetArticlesWebSocketParams(query="nvidia", extended=False) await client.websocket.connect(request_payload=payload, on_article=on_article) if __name__ == "__main__": asyncio.run(main()) ``` ```go // In Go the option lives on a directly constructed stream client. cfg := finlight.Config{APIKey: "YOUR_API_KEY"} ws := finlight.NewWebSocketClient(cfg, finlight.WebSocketOptions{ Takeover: true, // Automatically close oldest connection when limit is reached (default: false) }) for article := range ws.Stream(ctx, finlight.GetArticlesWebSocketParams{Query: "nvidia"}) { fmt.Println("New article received:", article.Title) } ``` ```csharp using Finlight.WebSockets; // In .NET the option lives on a directly constructed stream client. var ws = new ArticleWebSocketClient( new FinlightClientOptions { ApiKey = "YOUR_API_KEY" }, new FinlightWebSocketOptions { Takeover = true, // Automatically close oldest connection when limit is reached (default: false) }); await foreach (var article in ws.StreamAsync(new GetArticlesWebSocketParams { Query = "nvidia" }, cancellationToken)) { Console.WriteLine($"New article received: {article.Title}"); } ``` ```java FinlightClient client = FinlightClient.create( FinlightConfig.of("YOUR_API_KEY"), WebSocketOptions.builder() .takeover(true) // Automatically close oldest connection when limit is reached (default: false) .build()); client.webSocket().connect( GetArticlesWebSocketParams.builder().query("nvidia").build(), article -> System.out.println("New article received: " + article.title())); ``` ```ruby require "finlight/client" client = Finlight::Client.new(api_key: "YOUR_API_KEY") websocket = client.websocket( takeover: true # Automatically close oldest connection when limit is reached (default: false) ) websocket.connect(query: "nvidia") do |article| puts "New article received: #{article.title}" end ``` ```rust use finlight_client::{Config, GetArticlesWebSocketParams, WebSocketClient, WebSocketOptions}; use futures_util::StreamExt; // In Rust the option lives on a directly constructed stream client. let ws = WebSocketClient::new( Config::new("YOUR_API_KEY"), WebSocketOptions { takeover: true, // Automatically close oldest connection when limit is reached (default: false) ..Default::default() }, ); let mut stream = ws.stream(GetArticlesWebSocketParams { query: Some("nvidia".into()), ..Default::default() }); while let Some(item) = stream.next().await { println!("New article received: {}", item?.title); } ``` With `takeover: true`, if you've reached your connection limit, the new connection will automatically replace the oldest existing connection. This is useful during development or when redeploying applications. In production, you may want to keep the default (`takeover: false`) to maintain explicit control over your connections. ## What's Next? Now that you’ve successfully connected to the WebSocket API and received real-time articles, here are a few next steps you may find helpful: - Explore filtering by `source` or `extended` queries to refine the articles you receive. - Adjust your `query` parameters as needed to track different companies, indices, or financial topics. - Review your usage and connection minutes in the finlight Dashboard to stay within the free tier limits. --- # Basics URL: https://docs.finlight.me/en/v2/websocket-basics/ The finlight.me WebSocket API provides a continuous, real-time stream of financial news articles, delivered the moment they become available. Unlike traditional REST endpoints that require periodic polling, the WebSocket approach allows you to maintain a persistent connection and receive updates without making repeated requests. This leads to faster data delivery, efficient resource usage, and an enhanced user experience. In this guide, you’ll learn the fundamental steps to connect, authenticate, and keep the connection alive with the finlight.me WebSocket API. **Note**: To use websocket features, you need to have a paid subscription. The free tier does not include the WebSocket feature. You need at least a subscription with WebSocket features. --- ## Connecting to the WebSocket To start receiving real-time financial news updates, you need to establish a WebSocket connection to the finlight.me server. This connection remains open until either you or the server closes it. As soon as the connection is established, you can begin subscribing to article streams and receive messages as new articles are published. **NOTE**: The WebSocket API technically disconnects after 2 hours. However, our typescript or python client library handles this automatically by reconnecting for you. You can also manually reconnect if needed. - **WebSocket Endpoint**: ```plaintext wss://wss.finlight.me ``` **Key Points:** - **Real-Time Data**: The WebSocket protocol enables a full-duplex connection, meaning data can flow to and from the server in real-time. - **Publish/Subscribe Model**: Once connected, you can specify your query (e.g., `query: "nvidia"`) and the server will immediately send the latest matching article, followed by any new articles as they become available. - **No Repeated Polling**: Rather than continuously polling the server for new data, the server pushes new articles to you, reducing overhead and latency. ### Managing Connection Limits with Takeover Each subscription tier includes a **fixed number of parallel WebSocket connections**. If you attempt to open more connections than your tier allows, you have two options: 1. **Default behavior (`takeover: false`)**: The new connection attempt will be rejected, and you'll receive an error indicating you've reached your connection limit. 2. **Takeover mode (`takeover: true`)**: The oldest existing connection will be automatically closed, and the new connection will take its place. **Example with Takeover Enabled:** **Takeover:** ```typescript const client = new FinlightApi( { apiKey: 'YOUR_API_KEY', }, { // WebSocket-specific options takeover: true, // Automatically close oldest connection when limit is reached }, ) client.websocket.connect( { query: 'nvidia', language: 'en' }, (article) => { console.log('New article received:', article) }, ) ``` ```python from finlight_client import FinlightApi, ApiConfig, WebSocketOptions from finlight_client.models import GetArticlesWebSocketParams async def main(): client = FinlightApi( config=ApiConfig(api_key="YOUR_API_KEY"), websocket_options=WebSocketOptions(takeover=True) ) payload = GetArticlesWebSocketParams(query="nvidia", language="en") await client.websocket.connect(request_payload=payload, on_article=print) if __name__ == "__main__": asyncio.run(main()) ``` ```go // In Go, takeover is set on a directly constructed stream client. ws := finlight.NewWebSocketClient( finlight.Config{APIKey: "YOUR_API_KEY"}, finlight.WebSocketOptions{Takeover: true}, ) for article := range ws.Stream(ctx, finlight.GetArticlesWebSocketParams{ Query: "nvidia", Language: "en", }) { fmt.Println("New article received:", article.Title) } ``` ```csharp using Finlight.WebSockets; // In .NET, takeover is set on a directly constructed stream client. var ws = new ArticleWebSocketClient( new FinlightClientOptions { ApiKey = "YOUR_API_KEY" }, new FinlightWebSocketOptions { Takeover = true }); await foreach (var article in ws.StreamAsync(new GetArticlesWebSocketParams { Query = "nvidia", Language = "en", }, cancellationToken)) { Console.WriteLine($"New article received: {article.Title}"); } ``` ```java FinlightClient client = FinlightClient.create( FinlightConfig.of("YOUR_API_KEY"), WebSocketOptions.builder().takeover(true).build()); client.webSocket().connect( GetArticlesWebSocketParams.builder() .query("nvidia") .language("en") .build(), article -> System.out.println("New article received: " + article.title())); ``` ```ruby require "finlight/client" client = Finlight::Client.new(api_key: "YOUR_API_KEY") client.websocket(takeover: true).connect(query: "nvidia", language: "en") do |article| puts "New article received: #{article.title}" end ``` ```rust use finlight_client::{Config, GetArticlesWebSocketParams, WebSocketClient, WebSocketOptions}; use futures_util::StreamExt; // In Rust, takeover is set on a directly constructed stream client. let ws = WebSocketClient::new( Config::new("YOUR_API_KEY"), WebSocketOptions { takeover: true, ..Default::default() }, ); let mut stream = ws.stream(GetArticlesWebSocketParams { query: Some("nvidia".into()), language: Some("en".into()), ..Default::default() }); while let Some(item) = stream.next().await { println!("New article received: {}", item?.title); } ``` **When to Use Takeover:** - **Development/Testing**: Useful when you're frequently restarting your application and don't want to manually close existing connections. - **Single Active Instance**: When you want to ensure only the most recent connection instance is active. - **Automatic Migration**: When migrating between servers or redeploying your application. **When to Avoid Takeover:** - **Production Environments**: Where you want explicit control over connection management. - **Multiple Legitimate Connections**: When you intentionally run multiple connection instances for different purposes. - **Debugging**: When you need to understand why connection limits are being reached. --- ## Authentication To ensure secure and authorized access, all WebSocket connections to finlight.me must be authenticated using your API key. This key verifies that you have the necessary permissions and access rights to receive real-time content. Include your API key in the initial WebSocket handshake request headers. Most WebSocket client libraries allow you to specify additional headers when creating the connection. - **Header**: ```plaintext x-api-key: YOUR_API_KEY ``` **How to Get an API Key:** - Sign up at [the finlight Dashboard](https://app.finlight.me). - Navigate to the **API Keys** section to create and manage your keys. The snippets below show the raw wire protocol for building your own client. If you use one of the [official client libraries](https://docs.finlight.me/en/v2/client-libraries/), the handshake, authentication and keepalive are handled for you and none of this is necessary. **Code Snippet (Node.js Example):** ```javascript const WebSocket = require('ws') const socket = new WebSocket('wss://wss.finlight.me', { headers: { 'x-api-key': 'YOUR_API_KEY', }, }) socket.on('open', () => { console.log('Connected to finlight.me WebSocket!') // You can now send a subscription request to start receiving articles }) socket.on('error', (err) => { console.error('WebSocket error:', err) }) ``` --- ## Keeping the Connection Alive (Ping/Pong Mechanism) WebSocket connections can remain open for extended periods, but network conditions, proxies, and firewalls may drop inactive connections. To mitigate this, finlight.me supports a **ping/pong** keep-alive mechanism. **How It Works:** - **Client Sends `ping`**: At regular intervals (about every 25 seconds), the client sends a `ping` message to the server. The server marks a connection stale after ~60 seconds without activity, so keep the interval well under that (our client libraries use 25 seconds). - **Server Responds `pong`**: The server replies with a `pong` message, indicating the connection is still alive. - **No Response Handling**: If the client doesn’t receive a `pong` within a certain timeframe, it can assume the connection is lost and attempt to reconnect. This simple heartbeat ensures that both the client and server know the connection is still active and can exchange data without interruption. **Example (Node.js with setInterval):** ```javascript socket.on('open', () => { console.log('Connected to finlight WebSocket') // Send a ping every 25 seconds const pingInterval = setInterval( () => { if (socket.readyState === WebSocket.OPEN) { console.log('Sending ping...') socket.send(JSON.stringify({ action: 'ping' })) } }, 25 * 1000, ) // 25 seconds in milliseconds socket.on('message', (data) => { const message = JSON.parse(data) if (message.action === 'pong') { console.log('Received pong, connection is alive.') } else { // Handle other messages, such as incoming articles console.log('Received message:', message) } }) socket.on('close', () => { clearInterval(pingInterval) console.log('WebSocket connection closed.') }) }) ``` **Why is Ping/Pong Important?** - **Long-Running Connections**: Many applications rely on continuously running WebSocket connections. Without a keep-alive mechanism, these connections may silently fail. - **Network Reliability**: Ping/pong checks ensure that transient network issues don’t cause the client to remain unaware of a broken connection. - **Resource Efficiency**: Quickly detecting a lost connection helps the client conserve resources by not waiting indefinitely for new data that will never arrive. --- ## Connection Duration Limits finlight.me’s WebSocket infrastructure is powered by **AWS API Gateway**, which imposes a **hard 2-hour maximum connection duration** per WebSocket session. This is a platform-level limit — regardless of activity, all connections are closed after 2 hours by AWS. ### What This Means for You * **Your connection will be closed automatically after 2 hours**, even if it’s actively receiving data or sending pings. * This behavior is expected and not indicative of an error or network issue. * To maintain a seamless experience, you need to **reconnect after each 2-hour window**. ### We've Got You Covered Both our **Python** and **TypeScript** client libraries handle this transparently: * When the server closes the connection after 2 hours, the client detects the disconnect. * It then **automatically attempts to reconnect**, preserving your stream with minimal interruption. * This ensures continuous data flow without manual intervention. If you’re building your own client without using our libraries, be sure to implement reconnect logic on your end to handle the 2-hour limit gracefully. --- By understanding these basics—connecting securely, authenticating your requests, and maintaining the connection with a ping/pong heartbeat—you’re well on your way to efficiently integrating finlight.me’s WebSocket API into your application. From here, you can explore subscription messages, filters like `source` or `language`, and handle incoming articles to build rich, real-time financial news experiences. --- # Enhanced - Subscribe to articles URL: https://docs.finlight.me/en/v2/websocket-subscribe/ The finlight.me WebSocket API allows you to subscribe to article updates in real-time. Once connected and subscribed, you receive the latest article matching your query immediately, followed by any newly published articles that match your criteria as they appear. --- ## Article model The response article model contains all the information about an article, such as the link, title, publish date and source. It also contains a sentiment and its confidence about that. - `link` (string): URL to the full article. - `source` (string): Source website. E.g. `www.reuters.com` - `title` (string): Title of the article. - `summary` (string): Summary of the article if existing. Can be nullable. - `publishDate` (Date): Publication date as ISO date. - `createdAt` (Date): Internal creation date of the article in the finlight system as ISO date. - `revisedDate` (Date | null): Date the article was last revised after initial publication. `null` when the article has never been revised. Present when `includeUpdates` is enabled and the article has been revised. - `isUpdate` (boolean): `true` when this delivery is triggered by a post-publication update to the article. Only present when `includeUpdates` is enabled. - `language` (string): Language code in [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1). E.g. `en` | `de` | `fr` - `sentiment` (string): Sentiment analysis result. Values can be `positive` | `neutral` |`negative` - `confidence` (number): Confidence level of sentiment analysis from 0 to 1. - `images` (string[]): Array of image URLs from the article. - `countries` (string[]): Array of country codes in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format representing the countries related to the article. E.g. `["US", "GB", "DE"]`. Can be empty. - `categories` (string[]): Array of article categories. Possible values: `markets` | `economy` | `business` | `politics` | `geopolitics` | `regulation` | `technology` | `energy` | `commodities` | `crypto` | `health` | `climate` | `security`. Can be empty. - `companies` (Company[]): Array of companies that are mentioned in the article. Is only shown/available with [specific subscription tier](https://finlight.me/pricing). Can be nullable. ## Company model The response company model contains information about a company that is mentioned in an article. It includes details like the company name, ticker symbol, industry, and more. - `companyId` (number): Unique identifier for the company. - `confidence` (number): Confidence level of the company identification, between 0 and 1. - `country` (string): Country where the company is based in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. E.g. `US` | `DE` | `GB` - `exchange` (string): Stock exchange where the company is listed. - `industry` (string): Industry sector of the company. E.g. `Biotechnology, Technology` - `name` (string): Full name of the company. E.g. `Apple Inc.` - `sector` (string): Sector of the company. E.g. `Technology` | `Health Care` - `ticker` (string): Stock ticker symbol of the company. E.g. `AAPL` | `GOOGL` - `isin` (string): International Securities Identification Number (ISIN) of the company. E.g. `US0378331005` - `openfigi` (string): OpenFIGI identifier for the company. E.g. `BBG000B9XRY4` - `primaryListing` (object): Primary stock exchange listing information for the company. - `primaryListing.ticker` (string): Primary ticker symbol on the main exchange. - `primaryListing.exchangeCode` (string): Code of the primary exchange where the stock is listed. - `primaryListing.exchangeCountry` (string): Country of the primary exchange where the stock is listed. - `isins` (string[]): Array of International Securities Identification Numbers (ISINs) for the company. - `otherListings` (object[]): Array of other stock exchange listings for the company. - `otherListings[].ticker` (string): Ticker symbol on the alternative exchange. - `otherListings[].exchangeCode` (string): Code of the alternative exchange where the stock is listed. - `otherListings[].exchangeCountry` (string): Country of the alternative exchange where the stock is listed. --- ## Fetch articles (WEBSOCKET default route) When you subscribe, you’ll first receive the latest article matching your query, followed by any new articles as they are published. When subscribing, you can specify various parameters to filter the articles you receive: - `query` (string): Search query to find relevant articles. [Advanced queries](https://docs.finlight.me/v2/advanced-query-building/) - `sources` (string[]): Filter by article single or multiple sources. E.g. ["www.reuters.com", "www.cnbc.com"]. See source endpoint for valid values. **Supports wildcard `"*"`** to include all sources. - `optInSources` (string[]): Additional sources to include on top of your default source set. See source endpoint for valid values. - `excludeSources` (string[]): Excludes single or multiple sources. E.g. ["www.reuters.com", "www.cnbc.com"]. See source endpoint for valid values. - `tickers` (string[]): Filter by stock ticker symbols (String Array). This will return articles that mention these tickers. **Supports wildcard `"*"`** to include all tickers. - `countries` (string[]): Filter by the countries an article is about, using [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country codes (String Array). E.g. `["US", "GB", "DE"]`. This matches the article's `countries` field, not the publisher's country, a company's domicile, or a listing market. - `categories` (string[]): Filter by article category (String Array). Possible values: `markets`, `economy`, `business`, `politics`, `geopolitics`, `regulation`, `technology`, `energy`, `commodities`, `crypto`, `health`, `climate`, `security`. - `includeEntities` (boolean, default: false): Includes the companies mentioned in the article. Requires a specific subscription tier. - `language` (string, default: en): Filter by language ([ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1)). **Defaults to `en`, which returns English only and excludes other languages** — see [Language & Coverage](https://docs.finlight.me/en/v2/advanced-query-building/#language-and-multilingual-coverage). - `includeUpdates` (boolean, default: false): When enabled, updated articles are re-delivered with `isUpdate=true` and a `revisedDate` timestamp. Useful for monitoring article corrections or content additions after initial publication. - `extended` (boolean): **(Deprecated)** Legacy flag — accepted for backward compatibility but ignored by the server. It has no effect on the articles you receive. **Request (WEBSOCKET /):** ```typescript const client = new FinlightApi({ apiKey: 'YOUR_API_KEY', // Replace with your API key }) client.websocket.connect( { query: 'Nvidia', language: 'en', extended: true, countries: ['US', 'GB'], }, (article) => { console.log('New article received:', article) }, ) ``` ```python from finlight_client import FinlightApi, ApiConfig from finlight_client.models import GetArticlesWebSocketParams def on_article(data): print(data) async def main(): client = FinlightApi( config=ApiConfig( api_key="YOUR_API_KEY" ) ) payload = GetArticlesWebSocketParams( query="Nvidia", sources=["www.reuters.com"], language="en", extended=True, countries=["US", "GB"] ) await client.websocket.connect(request_payload=payload, on_article=on_article) if __name__ == "__main__": asyncio.run(main()) ``` ```go client, err := finlight.New(finlight.Config{APIKey: "YOUR_API_KEY"}) if err != nil { log.Fatal(err) } for article := range client.Websocket.Stream(ctx, finlight.GetArticlesWebSocketParams{ Query: "Nvidia", Language: "en", Extended: true, Countries: []string{"US", "GB"}, }) { fmt.Println("New article received:", article.Title) } if err := client.Websocket.Err(); err != nil { log.Fatal(err) } ``` ```csharp using Finlight; using var client = new FinlightClient("YOUR_API_KEY"); await foreach (var article in client.WebSocket.StreamAsync(new GetArticlesWebSocketParams { Query = "Nvidia", Language = "en", Extended = true, Countries = new[] { "US", "GB" }, }, cancellationToken)) { Console.WriteLine($"New article received: {article.Title}"); } ``` ```java FinlightClient client = FinlightClient.create("YOUR_API_KEY"); client.webSocket().connect( GetArticlesWebSocketParams.builder() .query("Nvidia") .language("en") .extended(true) .countries(List.of("US", "GB")) .build(), article -> System.out.println("New article received: " + article.title())); ``` ```ruby require "finlight/client" client = Finlight::Client.new(api_key: "YOUR_API_KEY") client.websocket.connect( query: "Nvidia", language: "en", extended: true, countries: %w[US GB] ) do |article| puts "New article received: #{article.title}" end ``` ```rust use finlight_client::{Client, Config, GetArticlesWebSocketParams}; use futures_util::StreamExt; let client = Client::new(Config::new("YOUR_API_KEY"))?; let mut stream = client.websocket.stream(GetArticlesWebSocketParams { query: Some("Nvidia".into()), language: Some("en".into()), extended: Some(true), countries: Some(vec!["US".into(), "GB".into()]), ..Default::default() }); while let Some(item) = stream.next().await { let article = item?; println!("New article received: {}", article.title); } ``` > **Note:** > **Managing Connection Limits**: If your subscription tier limits the number of parallel WebSocket connections, you can use the `takeover` option to automatically close the oldest connection when attempting to open a new one beyond your limit. This prevents connection errors during development or application restarts. > > By default, `takeover` is set to `false`, which means new connections will be rejected if you've reached your limit. Enable it during development for convenience, but consider keeping it disabled in production for explicit connection management. In TypeScript, Python, Java and Ruby the option is set on the client you already have. In Go, C# and Rust the top-level client always uses the default stream options, so takeover is configured on a directly constructed stream client instead. See the [WebSocket Quickstart](https://docs.finlight.me/en/v2/websocket-quickstart/) for a complete, runnable example in every language. **Takeover:** ```typescript const client = new FinlightApi( { apiKey: 'YOUR_API_KEY', }, { takeover: true, // Automatically close oldest connection when limit is reached }, ) ``` ```python from finlight_client import FinlightApi, ApiConfig, WebSocketOptions client = FinlightApi( config=ApiConfig(api_key="YOUR_API_KEY"), websocket_options=WebSocketOptions(takeover=True) ) ``` ```go ws := finlight.NewWebSocketClient(cfg, finlight.WebSocketOptions{ Takeover: true, // Automatically close oldest connection when limit is reached }) ``` ```csharp using Finlight.WebSockets; var ws = new ArticleWebSocketClient( new FinlightClientOptions { ApiKey = "YOUR_API_KEY" }, new FinlightWebSocketOptions { Takeover = true }); ``` ```java FinlightClient client = FinlightClient.create( FinlightConfig.of("YOUR_API_KEY"), WebSocketOptions.builder().takeover(true).build()); ``` ```ruby websocket = client.websocket(takeover: true) ``` ```rust let ws = WebSocketClient::new( Config::new("YOUR_API_KEY"), WebSocketOptions { takeover: true, ..Default::default() }, ); ``` **Response:** ```json { "link": "https://www.example.com/article1", "source": "www.example.com", "title": "Stock Market Hits New Highs", "summary": "A brief summary of the article...", "publishDate": "2023-10-01T12:34:56Z", "createdAt": "2023-10-01T12:35:10Z", "language": "en", "sentiment": "positive", "confidence": 0.95, "images": [ "https://www.example.com/image1.jpg", "https://www.example.com/image2.jpg" ], "countries": ["US"], "categories": ["markets", "technology"], "companies": [ { "companyId": 41494, "confidence": 0.9335401058197021, "country": "US", "exchange": "XNAS", "industry": "Biotechnology: Pharmaceutical Preparations", "name": "Summit Therapeutics Inc. Common Stock", "sector": "Health Care", "ticker": "SMMT", "isin": "US86627T1088", "openfigi": "BBG01PH11VP5", "primaryListing": { "ticker": "SMMT", "exchangeCode": "XNAS", "exchangeCountry": "US" }, "isins": ["US86627T1088", "US86627T2088"], "otherListings": [ { "ticker": "SMMT.L", "exchangeCode": "XLON", "exchangeCountry": "GB" } ] } ] } ``` **Response (includeUpdates: true):** ```json { "link": "https://www.example.com/article1", "source": "www.example.com", "title": "Stock Market Hits New Highs — Updated", "summary": "An updated summary of the article...", "publishDate": "2023-10-01T12:34:56Z", "createdAt": "2023-10-01T12:35:10Z", "revisedDate": "2023-10-02T08:00:00Z", "isUpdate": true, "language": "en", "sentiment": "positive", "confidence": 0.95, "images": [ "https://www.example.com/image1.jpg" ], "countries": ["US"], "categories": ["markets"], "companies": [] } ``` You can keep the connection open and receive articles in real-time without additional requests. As new articles become available, they are pushed directly to your callback function. --- # Raw - Subscribe to articles URL: https://docs.finlight.me/en/v2/raw-websocket-subscribe/ The Raw WebSocket provides a **lightweight, streamlined** alternative to the [Enhanced WebSocket](https://docs.finlight.me/en/v2/websocket-subscribe/). It delivers core article data in real-time **without** ticker matching, AI enrichment, or company entity resolution. This makes it ideal for use cases where you need fast, basic article data without the overhead of advanced processing. > **Note:** > **Key differences from the Enhanced WebSocket:** > - **Endpoint**: `wss://wss.finlight.me/raw` (instead of `wss://wss.finlight.me`) > - **No initial data**: Unlike the Enhanced WebSocket, the Raw WebSocket does **not** send the latest matching article on connection or reconnection. You will only receive newly published articles after connecting. > - **No AI enrichment**: Articles are delivered without sentiment analysis, company matching, or ticker resolution. > - **Simplified parameters**: No `tickers`, `countries`, `includeEntities`, or `extended` parameters. --- ## Article model The Raw WebSocket returns a simplified article model with core fields only. No company entities or AI-generated enrichments are included. - `link` (string): URL to the full article. - `source` (string): Source website. E.g. `www.reuters.com` - `title` (string): Title of the article. - `summary` (string): Summary of the article if existing. Can be nullable. - `publishDate` (Date): Publication date as ISO date. - `createdAt` (Date): Internal creation date of the article in the finlight system as ISO date. - `revisedDate` (Date | null): Date the article was last revised after initial publication. `null` when the article has never been revised. Present when `includeUpdates` is enabled and the article has been revised. - `isUpdate` (boolean): `true` when this delivery is triggered by a post-publication update to the article. Only present when `includeUpdates` is enabled. - `language` (string): Language code in [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1). E.g. `en` | `de` | `fr` - `images` (string[]): Array of image URLs from the article. - `categories` (string[]): Array of article categories. Possible values: `markets` | `economy` | `business` | `politics` | `geopolitics` | `regulation` | `technology` | `energy` | `commodities` | `crypto` | `health` | `climate` | `security`. Can be empty. --- ## Fetch articles (WEBSOCKET /raw) After connecting, you will only receive **newly published articles** that match your criteria. No initial/historical article is sent on connection. When subscribing, you can specify the following parameters to filter the articles you receive: - `query` (string): Search query to find relevant articles. Supports field-level filtering for `source`, `title`, and `summary` fields. [Advanced queries](https://docs.finlight.me/en/v2/advanced-query-building/#raw-websocket-query-fields) - `sources` (string[]): Filter by single or multiple sources. E.g. `["www.reuters.com", "www.cnbc.com"]`. See source endpoint for valid values. - `excludeSources` (string[]): Exclude single or multiple sources. E.g. `["www.reuters.com", "www.cnbc.com"]`. See source endpoint for valid values. - `language` (string, default: en): Filter by language ([ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1)). **Defaults to `en`, which returns English only and excludes other languages** — see [Language & Coverage](https://docs.finlight.me/en/v2/advanced-query-building/#language-and-multilingual-coverage). - `includeUpdates` (boolean, default: false): When enabled, updated articles are re-delivered with `isUpdate=true` and a `revisedDate` timestamp. **Request (WEBSOCKET /raw):** ```typescript const client = new FinlightApi( { apiKey: 'YOUR_API_KEY', // Replace with your API key }, { takeover: true, // WebSocket options }, ) client.rawWebsocket.connect( { query: 'Nvidia', language: 'en', sources: ['www.reuters.com', 'www.cnbc.com'], }, (article) => { console.log('New article received:', article) }, ) ``` ```python from finlight_client import FinlightApi, ApiConfig, RawWebSocketOptions from finlight_client.models import GetRawArticlesWebSocketParams def on_article(data): print(data) async def main(): client = FinlightApi( config=ApiConfig( api_key="YOUR_API_KEY" ), raw_websocket_options=RawWebSocketOptions( takeover=True ) ) payload = GetRawArticlesWebSocketParams( query="Nvidia", sources=["www.reuters.com", "www.cnbc.com"], language="en", ) await client.raw_websocket.connect(request_payload=payload, on_article=on_article) if __name__ == "__main__": asyncio.run(main()) ``` ```go // Takeover is a stream-client option, so build the raw client directly. cfg := finlight.Config{APIKey: "YOUR_API_KEY"} ws := finlight.NewRawWebSocketClient(cfg, finlight.WebSocketOptions{Takeover: true}) for article := range ws.Stream(ctx, finlight.GetRawArticlesWebSocketParams{ Query: "Nvidia", Language: "en", Sources: []string{"www.reuters.com", "www.cnbc.com"}, }) { fmt.Println("New article received:", article.Title) } if err := ws.Err(); err != nil { log.Fatal(err) } ``` ```csharp using Finlight.WebSockets; // Takeover is a stream-client option, so build the raw client directly. var ws = new RawArticleWebSocketClient( new FinlightClientOptions { ApiKey = "YOUR_API_KEY" }, new FinlightWebSocketOptions { Takeover = true }); await foreach (var article in ws.StreamAsync(new GetRawArticlesWebSocketParams { Query = "Nvidia", Language = "en", Sources = new[] { "www.reuters.com", "www.cnbc.com" }, }, cancellationToken)) { Console.WriteLine($"New article received: {article.Title}"); } ``` ```java FinlightClient client = FinlightClient.create( FinlightConfig.of("YOUR_API_KEY"), WebSocketOptions.builder().takeover(true).build()); client.rawWebSocket().connect( GetRawArticlesWebSocketParams.builder() .query("Nvidia") .language("en") .sources(List.of("www.reuters.com", "www.cnbc.com")) .build(), article -> System.out.println("New article received: " + article.title())); ``` ```ruby require "finlight/client" client = Finlight::Client.new(api_key: "YOUR_API_KEY") websocket = client.raw_websocket(takeover: true) websocket.connect( query: "Nvidia", language: "en", sources: %w[www.reuters.com www.cnbc.com] ) do |article| puts "New article received: #{article.title}" end ``` ```rust use finlight_client::{Config, GetRawArticlesWebSocketParams, RawWebSocketClient, WebSocketOptions}; use futures_util::StreamExt; // Takeover is a stream-client option, so build the raw client directly. let ws = RawWebSocketClient::new( Config::new("YOUR_API_KEY"), WebSocketOptions { takeover: true, ..Default::default() }, ); let mut stream = ws.stream(GetRawArticlesWebSocketParams { query: Some("Nvidia".into()), language: Some("en".into()), sources: Some(vec!["www.reuters.com".into(), "www.cnbc.com".into()]), ..Default::default() }); while let Some(item) = stream.next().await { println!("New article received: {}", item?.title); } ``` **Response:** ```json { "link": "https://www.example.com/article1", "source": "www.example.com", "title": "Stock Market Hits New Highs", "summary": "A brief summary of the article...", "publishDate": "2023-10-01T12:34:56Z", "createdAt": "2023-10-01T12:35:10Z", "language": "en", "images": [ "https://www.example.com/image1.jpg", "https://www.example.com/image2.jpg" ], "categories": ["markets"] } ``` **Response (includeUpdates: true):** ```json { "link": "https://www.example.com/article1", "source": "www.example.com", "title": "Stock Market Hits New Highs — Updated", "summary": "An updated summary of the article...", "publishDate": "2023-10-01T12:34:56Z", "createdAt": "2023-10-01T12:35:10Z", "revisedDate": "2023-10-02T08:00:00Z", "isUpdate": true, "language": "en", "images": [ "https://www.example.com/image1.jpg" ], "categories": ["markets"] } ``` ### Query Field-Level Filtering The Raw WebSocket supports field-level filtering within the `query` parameter for the following fields: - **`source`** - Filter by article source - **`title`** - Filter by article title content - **`summary`** - Filter by article summary content **Examples:** ```plaintext query=title:Nvidia ``` Returns articles where the title contains "Nvidia". ```plaintext query=summary:earnings +title:Tesla ``` Returns articles where the summary mentions "earnings" and the title contains "Tesla". ```plaintext query=source:www.reuters.com -crypto ``` Returns articles from Reuters, excluding those mentioning "crypto". See the [Advanced Query Building](https://docs.finlight.me/en/v2/advanced-query-building/#raw-websocket-query-fields) guide for more details on query syntax. --- ### Connection Behavior - **Authentication**: Uses the same `x-api-key` header as the Enhanced WebSocket. See [WebSocket Basics](https://docs.finlight.me/en/v2/websocket-basics/) for details. - **Ping/Pong**: The same keep-alive mechanism applies. Send periodic `ping` messages to maintain the connection. - **Connection Duration**: Subject to the same 2-hour connection limit. Implement reconnect logic accordingly. - **No Initial Data**: Unlike the Enhanced WebSocket, connecting or reconnecting does **not** return the latest matching article. Only newly published articles are delivered after connection. --- # Browser WebSocket URL: https://docs.finlight.me/en/v2/browser-websocket/ Connect to the finlight.me WebSocket API directly from a web browser using the **native WebSocket API**. This is ideal for dashboards, trading terminals, and any frontend application that needs real-time article updates without a server-side proxy. > **Note:** > The browser WebSocket API does not support custom headers. Authentication is handled via **query parameters** instead of the `x-api-key` header. Your API key will be visible in the WebSocket URL — only use this approach in environments where that is acceptable (e.g., authenticated dashboards). Never expose your API key in public-facing client-side code. --- ## How It Works 1. **Connect** to `wss://wss.finlight.me` (enhanced) or `wss://wss.finlight.me/raw` (raw) with your API key as a query parameter 2. **Subscribe** by sending a JSON message with your filter criteria and a `clientNonce` 3. **Receive** an `admit` message confirming your connection, followed by `sendArticle` messages as articles arrive 4. **Keep alive** by sending `ping` messages every 25 seconds 5. **Disconnect** by calling `ws.close()` --- ## Connection URLs - `Enhanced` (wss://wss.finlight.me): Articles with full enrichment: sentiment analysis, entity extraction, categories, and full content (based on your subscription tier). - `Raw` (wss://wss.finlight.me/raw): Low-latency raw articles without enrichment. Best for speed-first use cases where you need articles as fast as possible. ## Query Parameters - `apiKey` (string): Your finlight API key. Used for authentication since browser WebSocket cannot set custom headers. - `takeover` (string, default: false): Set to `"true"` to automatically replace the oldest connection when your concurrent connection limit is reached. - `clientVersion` (string): Optional identifier for your client application. E.g. `"my-dashboard/1.0"` --- ## Subscribe Message After the connection opens, send a JSON message to subscribe to articles. The server will respond with an `admit` message, then begin pushing matching articles. - `clientNonce` (string): A unique identifier (e.g., UUID) for this subscription request. The server echoes it back in the `admit` response. - `query` (string): Search query to find relevant articles. Supports [advanced queries](https://docs.finlight.me/v2/advanced-query-building/). - `sources` (string[]): Filter by source domains. E.g. `["www.reuters.com", "www.cnbc.com"]` - `excludeSources` (string[]): Exclude specific source domains. - `tickers` (string[]): Filter by stock ticker symbols. E.g. `["AAPL", "NVDA"]` (Enhanced only) - `countries` (string[]): Filter by country codes in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). E.g. `["US", "DE"]` (Enhanced only) - `language` (string): Filter by language ([ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1)). **Defaults to `en`, which returns English only and excludes other languages** — see [Language & Coverage](https://docs.finlight.me/en/v2/advanced-query-building/#language-and-multilingual-coverage). --- ## Server Messages The server sends JSON messages with an `action` field indicating the message type: - `admit` (object): Sent after a successful handshake. Contains `leaseId`, `serverNow` (timestamp), and your `clientNonce`. - `sendArticle` (object): A new article matching your subscription. The article data is in the `data` field. - `pong` (object): Response to your `ping` heartbeat. - `preempted` (object): Your connection was replaced by another session (when another client connected with `takeover: true`). - `error` (object): An error occurred. Check the `data` or `error` field for details. --- ## Complete Example (WEBSOCKET Browser) A minimal, framework-agnostic browser WebSocket client with automatic reconnection and heartbeat: - Authenticates via query parameters - Sends a subscribe message on connect - Maintains a 25-second heartbeat interval - Reconnects with exponential backoff (500ms to 10s) - Handles all server message types **Browser Client (WEBSOCKET wss://wss.finlight.me):** **Vanilla JavaScript:** ```js const API_KEY = 'YOUR_API_KEY' const WSS_URL = 'wss://wss.finlight.me' // Use '/raw' path for raw articles let ws = null let pingInterval = null let reconnectTimeout = null let reconnectAttempt = 0 function connect(filters = {}) { const params = new URLSearchParams({ apiKey: API_KEY, takeover: 'true', clientVersion: 'my-app/1.0', }) const url = `${WSS_URL}?${params}` ws = new WebSocket(url) ws.onopen = () => { console.log('Connected') reconnectAttempt = 0 // Send subscription with filters ws.send(JSON.stringify({ clientNonce: crypto.randomUUID(), query: filters.query || '', language: filters.language || 'en', sources: filters.sources || [], tickers: filters.tickers || [], countries: filters.countries || [], })) // Start heartbeat pingInterval = setInterval(() => { if (ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ action: 'ping', t: Date.now(), })) } }, 25000) } ws.onmessage = (event) => { const msg = JSON.parse(event.data) switch (msg.action) { case 'admit': console.log('Admitted, lease:', msg.leaseId) break case 'sendArticle': console.log('Article:', msg.data.title) // Handle the article here break case 'pong': break // Heartbeat OK case 'preempted': console.warn('Connection replaced') break case 'error': console.error('Server error:', msg.data || msg.error) break } } ws.onclose = (event) => { clearInterval(pingInterval) // Don't reconnect on policy violations if (event.code === 1008 || event.code === 4002) { console.error('Connection blocked') return } // Exponential backoff reconnect const delay = Math.min(500 * 2 ** reconnectAttempt, 10000) reconnectAttempt++ console.log(`Reconnecting in ${delay}ms...`) reconnectTimeout = setTimeout(() => connect(filters), delay) } ws.onerror = () => console.error('WebSocket error') } function disconnect() { clearInterval(pingInterval) clearTimeout(reconnectTimeout) if (ws) ws.close(1000) } // Usage connect({ query: 'Nvidia', language: 'en', countries: ['US'] }) ``` **React Hook:** ```ts interface Article { link: string title: string source: string sentiment: string publishDate: string [key: string]: any } interface UseFinlightWsOptions { apiKey: string type?: 'enriched' | 'raw' filters?: { query?: string language?: string sources?: string[] tickers?: string[] countries?: string[] } onArticle?: (article: Article) => void } function useFinlightWebSocket({ apiKey, type = 'enriched', filters = {}, onArticle, }: UseFinlightWsOptions) { const wsRef = useRef(null) const pingRef = useRef>() const [connected, setConnected] = useState(false) const [error, setError] = useState(null) const connect = useCallback(() => { const base = 'wss://wss.finlight.me' const path = type === 'raw' ? '/raw' : '' const params = new URLSearchParams({ apiKey, takeover: 'true', }) const ws = new WebSocket(`${base}${path}?${params}`) wsRef.current = ws ws.onopen = () => { setConnected(true) setError(null) ws.send(JSON.stringify({ clientNonce: crypto.randomUUID(), ...filters, })) pingRef.current = setInterval(() => { if (ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ action: 'ping', t: Date.now() })) } }, 25000) } ws.onmessage = (event) => { const msg = JSON.parse(event.data) if (msg.action === 'sendArticle' && msg.data) { onArticle?.(msg.data) } else if (msg.action === 'error') { setError(msg.data || msg.error) } else if (msg.action === 'preempted') { setError('Connection replaced by another session') } } ws.onclose = () => { setConnected(false) clearInterval(pingRef.current) } ws.onerror = () => setError('WebSocket error') }, [apiKey, type, JSON.stringify(filters)]) const disconnect = useCallback(() => { clearInterval(pingRef.current) wsRef.current?.close(1000) wsRef.current = null }, []) useEffect(() => { return () => disconnect() }, []) return { connect, disconnect, connected, error } } // Usage in a component function NewsFeed() { const [articles, setArticles] = useState([]) const { connect, disconnect, connected, error } = useFinlightWebSocket({ apiKey: 'YOUR_API_KEY', filters: { query: 'Nvidia', language: 'en' }, onArticle: (article) => { setArticles((prev) => [article, ...prev]) }, }) return (
{error &&

{error}

} {articles.map((a) => (
{a.title}
))}
) } ``` **admit Response:** ```json { "action": "admit", "leaseId": "a1b2c3d4-e5f6-4789-abcd-ef0123456789", "serverNow": 1708185600000, "clientNonce": "your-uuid-here" } ``` **sendArticle Response:** ```json { "action": "sendArticle", "data": { "link": "https://www.reuters.com/technology/nvidia-2026-02-17", "source": "www.reuters.com", "title": "Nvidia Reports Record Revenue", "summary": "Nvidia announced record quarterly revenue...", "publishDate": "2026-02-17T10:30:00Z", "language": "en", "sentiment": "positive", "confidence": 0.92, "countries": ["US"], "categories": ["markets", "technology"], "companies": [ { "name": "NVIDIA Corporation", "ticker": "NVDA", "country": "US" } ] } } ``` --- ## Enhanced vs Raw | Feature | Enhanced (`/`) | Raw (`/raw`) | |---|---|---| | Sentiment analysis | Yes | No | | Entity extraction (companies) | Yes (tier-dependent) | No | | Categories (in payload) | Yes | Yes | | Full content | Yes (tier-dependent) | No | | Latency | Standard | Lowest | | Filter: `tickers` | Yes | No | | Filter: `countries` | Yes | No | | Filter: `query`, `sources`, `language` | Yes | Yes | > **Note:** > Raw WebSocket subscriptions only support `query`, `sources`, `excludeSources`, and `language` filters. Ticker and country filters are silently ignored on the raw endpoint. ## What's Next? - Review the [Enhanced Subscribe](https://docs.finlight.me/v2/websocket-subscribe/) page for the full article model and all available fields - Check [Raw Subscribe](https://docs.finlight.me/v2/raw-websocket-subscribe/) for raw-specific details - Learn about [Advanced Query Building](https://docs.finlight.me/v2/advanced-query-building/) to refine your filters - Use the [REST API](https://docs.finlight.me/v2/rest-endpoints/) for historical article lookups alongside your real-time stream --- # Quickstart URL: https://docs.finlight.me/en/v2/webhooks/ Get instant notifications when breaking news happens. Webhooks deliver real-time article updates directly to your application, eliminating the need for constant API polling. --- ## What are Webhooks? (CONCEPT Understanding) Think of webhooks as **instant notifications** for your application. When news breaks that matches your criteria, finlight immediately sends the article data to your specified endpoint. ### How Webhooks Work Here's the complete flow in simple terms: 1. **Configure** - Set up your webhook with specific news criteria 2. **Monitor** - Our system watches for new articles 24/7 3. **Match** - When an article meets your criteria, we detect it instantly 4. **Deliver** - We send the article data directly to your endpoint This **"reverse API"** approach means your app receives updates the moment they happen, rather than asking for them repeatedly. --- ## Getting Started (SETUP Quick Start) ### What You'll Need Before creating your first webhook, make sure you have: - **Active finlight subscription** with webhook access - **Public HTTPS endpoint** ready to receive webhook calls - **Dashboard access** at [app.finlight.me](https://app.finlight.me) ### Quick Access Jump straight to webhook creation by visiting [app.finlight.me/news-webhooks](https://app.finlight.me/news-webhooks) and logging into your finlight account. --- ## Creating Your First Webhook (TUTORIAL Step by Step) Follow this simple 4-step process to set up your webhook and start receiving real-time news updates. ### Step 1: Access the Webhook Creator 1. **Login** to your finlight dashboard at [app.finlight.me](https://app.finlight.me) 2. **Navigate** to **"Webhooks"** in the main menu 3. **Click** **"New Webhook"** to launch the setup wizard ### Step 2: Basic Details Give your webhook a clear identity and choose a delivery type: - **Name** - Choose something descriptive like "Breaking Tech News" or "Market Updates" - **Description** - Optional brief explanation of the webhook's purpose - **Delivery Type** - Select how articles should be delivered: - **Enriched** *(default)* — AI-processed payload with company data, sentiment, and full filtering options. See the [Enriched Webhooks](https://docs.finlight.me/en/v2/webhooks/enriched/) guide. - **Raw** — Faster delivery, simplified payload, limited filters. See the [Raw Webhooks](https://docs.finlight.me/en/v2/webhooks/raw/) guide. ### Step 3: Define Your News Criteria Configure filtering to receive only relevant articles. Available options depend on your chosen delivery type. See [Enriched Webhooks](https://docs.finlight.me/en/v2/webhooks/enriched/) or [Raw Webhooks](https://docs.finlight.me/en/v2/webhooks/raw/) for the complete filter reference for your type. ### Step 4: Set Destination & Security #### Webhook Destination Provide your endpoint URL where we'll send the news: - Must be a public HTTPS URL - Should respond quickly (under 5 seconds) #### Security Setup Choose how to secure your webhook endpoint: - **None** - No additional authentication (not recommended for production) - **Basic Authentication** - Username/password protection via HTTP Basic Auth - **Custom Header** - Send your API key in the `X-Finlight-Key` header - **Signature Validation** - Always included for payload verification via `X-Webhook-Signature` header **Note:** Signature validation is automatically enabled on all webhooks for payload integrity verification, regardless of your chosen authentication method. **Learn more** about implementing these security options in our [authentication guide](https://docs.finlight.me/en/v2/webhooks/authentication/). --- ## Testing Your Integration (TEST Validation) ### Built-in Testing Tools Before going live, validate your webhook setup: - **Dashboard Test Feature** - Send sample payloads to your endpoint - **Delivery Monitoring** - Track success rates and response times - **Error Diagnostics** - Debug failed deliveries For comprehensive testing instructions, payload examples, and troubleshooting tips, visit our [webhook testing guide](https://docs.finlight.me/en/v2/webhooks/testing/). --- ## Need Help? (SUPPORT Get Assistance) ### Quick Support Options **Payload & Filtering** See [Enriched Webhooks](https://docs.finlight.me/en/v2/webhooks/enriched/) or [Raw Webhooks](https://docs.finlight.me/en/v2/webhooks/raw/) for the article model and filter reference for your type. **Technical Setup** Visit our [authentication guide](https://docs.finlight.me/en/v2/webhooks/authentication/) and [testing guide](https://docs.finlight.me/en/v2/webhooks/testing/) for detailed implementation help. **General Support** Check our [support page](https://docs.finlight.me/en/v2/support/) for additional resources and contact information. **Dashboard Issues** Access your webhook management at [app.finlight.me](https://app.finlight.me) or contact support through the platform. --- ### Ready to Start? Webhooks transform how you receive news updates - from polling every few minutes to **instant delivery** the moment news breaks. **Start simple** with basic filtering criteria, then **expand gradually** as you discover what works best for your application. The finlight dashboard makes it easy to modify and optimize your webhooks anytime. **[Create your first webhook now →](https://app.finlight.me/news-webhooks)** --- # Enriched Webhooks URL: https://docs.finlight.me/en/v2/webhooks/enriched/ Enriched Webhooks deliver **AI-processed article data** with company entity resolution, sentiment analysis, and the full set of filtering options. > **Note:** > **Key capabilities of Enriched Webhooks:** > - **Full filtering** — filter by tickers, countries, categories, sources, language, and query > - **AI enrichment** — payloads include sentiment scores, company matches, and confidence values > - **Flexible content** — optionally include full article text and extracted entities via `includeContent` / `includeEntities` > - **Immutable type** — the delivery type (`enriched` or `raw`) is set at creation and cannot be changed afterwards --- ## Article model Enriched Webhooks deliver the complete article payload including AI-generated company data, sentiment analysis, and entity resolution. - `link` (string): URL to the full article. - `source` (string): Source website. E.g. `www.reuters.com` - `title` (string): Title of the article. - `summary` (string): Summary of the article if available. Can be nullable. - `publishDate` (Date): Publication date as ISO 8601 date string. - `createdAt` (Date): Internal creation date of the article in the finlight system as ISO 8601 date string. - `revisedDate` (Date | null): Date the article was last revised after initial publication. `null` when the article has never been revised. Present when `includeUpdates` is enabled and the article has been revised. - `isUpdate` (boolean): `true` when this delivery is triggered by a post-publication update. Only present when `includeUpdates` is enabled. - `language` (string): Language code in [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1). E.g. `en` | `de` | `fr` - `sentiment` (string): AI-generated sentiment of the article. Possible values: `positive` | `negative` | `neutral`. - `confidence` (number): Confidence score for the sentiment value, between `0` and `1`. - `images` (string[]): Array of image URLs from the article. - `countries` (string[]): Array of country codes in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. E.g. `["US", "GB"]`. Can be empty. - `categories` (string[]): Array of article categories. Possible values: `markets` | `economy` | `business` | `politics` | `geopolitics` | `regulation` | `technology` | `energy` | `commodities` | `crypto` | `health` | `climate` | `security`. Can be empty. - `companies` (Company[]): Array of matched company objects resolved by AI entity matching. Each company contains the following fields: - **`companyId`** `number` — internal finlight company identifier - **`confidence`** `number` — entity match confidence score (between 0 and 1) - **`name`** `string` — full company name - **`ticker`** `string` — primary ticker symbol. E.g. `AAPL` - **`exchange`** `string` — exchange code. E.g. `XNAS` - **`country`** `string` — country of primary listing (ISO 3166-1 alpha-2) - **`sector`** `string` — sector classification. E.g. `Technology` - **`industry`** `string` — industry classification - **`isin`** `string` — primary ISIN code - **`openfigi`** `string` — OpenFIGI identifier - **`primaryListing`** `object` — `{ ticker, exchangeCode, exchangeCountry }` - **`isins`** `string[]` — all known ISINs for the company - **`otherListings`** `object[]` — `[{ ticker, exchangeCode, exchangeCountry }]` --- ## Create an Enriched Webhook (WEBHOOK Delivery Type) When creating a webhook in the [finlight dashboard](https://app.finlight.me/news-webhooks), select **Enriched** as the delivery type in the first step of the setup wizard. This is the default option. The criteria step will show all available filter parameters. Enriched Webhooks deliver only **newly published articles** that match your criteria. Each delivery is a single article payload sent as an HTTP `POST` request to your endpoint. - `query` (string): Search query to find relevant articles. Supports boolean operators and field-level filtering. See the [Advanced Query Building](https://docs.finlight.me/en/v2/advanced-query-building/) guide. - `sources` (string[]): Limit delivery to articles from specific sources. E.g. `["www.reuters.com", "www.cnbc.com"]`. - `excludeSources` (string[]): Exclude articles from specific sources. E.g. `["www.example.com"]`. - `language` (string, default: en): Filter by article language ([ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1)). **Defaults to `en`, which returns English only and excludes other languages** — see [Language & Coverage](https://docs.finlight.me/en/v2/advanced-query-building/#language-and-multilingual-coverage). - `tickers` (string[]): Filter by stock ticker symbols. Only articles matched to these companies by AI entity resolution will be delivered. E.g. `["AAPL", "GOOGL", "TSLA"]`. - `countries` (string[]): Filter by country codes ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). Only articles about these countries will be delivered. This matches the article's `countries` field, not a company's domicile or a listing market. E.g. `["US", "GB", "DE"]`. - `categories` (string[]): Filter by article category. Possible values: `markets` | `economy` | `business` | `politics` | `geopolitics` | `regulation` | `technology` | `energy` | `commodities` | `crypto` | `health` | `climate` | `security`. - `includeContent` (boolean, default: false): **(Deprecated)** Include the full article body text in the payload. Requires a plan with full article access. - `includeEntities` (boolean, default: false): Include extracted entities (companies, people, locations) found in the article. - `excludeEmptyContent` (boolean, default: false): **(Deprecated)** Only deliver articles that have non-empty scraped content. Useful for filtering out articles whose body could not be retrieved. - `includeUpdates` (boolean, default: false): Re-deliver articles when they are updated after initial publication. Updated payloads include `isUpdate=true` and a `revisedDate` timestamp. **Response:** ```json { "link": "https://www.example.com/article1", "source": "www.example.com", "title": "Stock Market Hits New Highs", "summary": "A brief summary of the article...", "publishDate": "2023-10-01T12:34:56Z", "createdAt": "2023-10-01T12:35:10Z", "language": "en", "sentiment": "positive", "confidence": 0.95, "images": [ "https://www.example.com/image1.jpg", "https://www.example.com/image2.jpg" ], "countries": ["US"], "categories": ["markets", "health"], "companies": [ { "companyId": 41494, "confidence": 0.9335401058197021, "country": "US", "exchange": "XNAS", "industry": "Biotechnology: Pharmaceutical Preparations", "name": "Summit Therapeutics Inc. Common Stock", "sector": "Health Care", "ticker": "SMMT", "isin": "US86627T1088", "openfigi": "BBG01PH11VP5", "primaryListing": { "ticker": "SMMT", "exchangeCode": "XNAS", "exchangeCountry": "US" }, "isins": ["US86627T1088", "US86627T2088"], "otherListings": [ { "ticker": "SMMT.L", "exchangeCode": "XLON", "exchangeCountry": "GB" } ] } ] } ``` **Response (includeUpdates: true):** ```json { "link": "https://www.example.com/article1", "source": "www.example.com", "title": "Stock Market Hits New Highs — Updated", "summary": "An updated summary of the article...", "publishDate": "2023-10-01T12:34:56Z", "createdAt": "2023-10-01T12:35:10Z", "revisedDate": "2023-10-02T08:00:00Z", "isUpdate": true, "language": "en", "sentiment": "positive", "confidence": 0.95, "images": [ "https://www.example.com/image1.jpg" ], "countries": ["US"], "categories": ["markets"], "companies": [] } ``` --- ## Filtering Examples (EXAMPLES Combined Filters) Enriched Webhooks support combining all filter parameters. Here are common patterns: **Company research feed:** ```plaintext tickers: ["AAPL", "GOOGL"] sources: ["www.reuters.com", "www.bloomberg.com"] includeEntities: true ``` **Breaking market news:** ```plaintext query: "earnings OR revenue OR guidance" categories: ["markets", "economy"] language: "en" ``` **Regional sector focus:** ```plaintext countries: ["US", "CA"] query: "tech OR technology OR semiconductor" tickers: ["NVDA", "TSMC", "AMD"] ``` **European financial news:** ```plaintext countries: ["GB", "DE", "FR"] sources: ["www.reuters.com", "www.ft.com"] language: "en" ``` **Query syntax** supports boolean operators, quoted phrases, and exclusion: ```plaintext "Apple earnings" simple phrase (Apple OR iPhone) AND (earnings OR revenue) boolean groups Tesla NOT recall exclusion ``` See the [Advanced Query Building](https://docs.finlight.me/en/v2/advanced-query-building/) guide for the full query syntax reference. --- ## When to Use Enriched Webhooks (GUIDE Decision Help) **Choose Enriched when you:** - Need company/ticker-level filtering (`tickers`, `countries`, `categories`) - Want sentiment scores, confidence values, or entity resolution in the payload - Need to include full article content or extracted entities via `includeContent` / `includeEntities` - Are building equity monitoring, earnings tracking, or sector-specific news feeds **Choose Raw when you:** - Need the lowest possible delivery latency - Are building a high-throughput pipeline where enrichment data is not required - Only need to filter by keywords, sources, or language - Want a leaner payload to reduce processing overhead on your end For full details on Raw Webhook filtering options, see the [Raw Webhooks](https://docs.finlight.me/en/v2/webhooks/raw/) guide. --- # Raw Webhooks URL: https://docs.finlight.me/en/v2/webhooks/raw/ Raw Webhooks are a **lightweight, fast-delivery** alternative to standard (enriched) webhooks. They deliver core article data the moment it is published, skipping the AI enrichment pipeline entirely. > **Note:** > **Key differences from Enriched Webhooks:** > - **Faster delivery** — articles are pushed as soon as they are ingested, without waiting for sentiment analysis, entity resolution, or company matching. > - **Simplified filters** — only `query`, `sources`, `excludeSources`, `language`, and `includeUpdates` are supported. `tickers`, `countries`, `categories`, `includeContent`, `includeEntities`, and `excludeEmptyContent` are not available. > - **No AI enrichment** — payloads contain no `sentiment`, `confidence`, or `companies` data. > - **Query field-level filtering** — the `query` parameter supports field-level syntax for `source`, `title`, and `summary` only. > - **Immutable type** — the delivery type (`raw` or `enriched`) is set at creation and cannot be changed afterwards. --- ## Article model Raw Webhooks deliver a simplified article payload. No company entities, sentiment scores, or AI-generated enrichments are included. - `link` (string): URL to the full article. - `source` (string): Source website. E.g. `www.reuters.com` - `title` (string): Title of the article. - `summary` (string): Summary of the article if available. Can be nullable. - `publishDate` (Date): Publication date as ISO 8601 date string. - `createdAt` (Date): Internal creation date of the article in the finlight system as ISO 8601 date string. - `revisedDate` (Date | null): Date the article was last revised after initial publication. `null` when the article has never been revised. Present when `includeUpdates` is enabled and the article has been revised. - `isUpdate` (boolean): `true` when this delivery is triggered by a post-publication update. Only present when `includeUpdates` is enabled. - `language` (string): Language code in [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1). E.g. `en` | `de` | `fr` - `images` (string[]): Array of image URLs from the article. - `categories` (string[]): Array of article categories. Possible values: `markets` | `economy` | `business` | `politics` | `geopolitics` | `regulation` | `technology` | `energy` | `commodities` | `crypto` | `health` | `climate` | `security`. Can be empty. --- ## Create a Raw Webhook (WEBHOOK Delivery Type) When creating a webhook in the [finlight dashboard](https://app.finlight.me/news-webhooks), select **Raw** as the delivery type in the first step of the setup wizard. The criteria step will then show only the four supported filter parameters. Raw Webhooks deliver only **newly published articles** that match your criteria. Each delivery is a single article payload sent as an HTTP `POST` request to your endpoint. - `query` (string): Search query to find relevant articles. Supports field-level filtering for `source`, `title`, and `summary` fields. See [query field-level filtering](#query-field-level-filtering) below. - `sources` (string[]): Limit delivery to articles from specific sources. E.g. `["www.reuters.com", "www.cnbc.com"]`. See the sources endpoint for valid values. - `excludeSources` (string[]): Exclude articles from specific sources. E.g. `["www.example.com"]`. - `language` (string, default: en): Filter by article language ([ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1)). **Defaults to `en`, which returns English only and excludes other languages** — see [Language & Coverage](https://docs.finlight.me/en/v2/advanced-query-building/#language-and-multilingual-coverage). - `includeUpdates` (boolean, default: false): Re-deliver articles when they are updated after initial publication. Updated payloads include `isUpdate=true` and a `revisedDate` timestamp. **Response:** ```json { "link": "https://www.example.com/article1", "source": "www.example.com", "title": "Stock Market Hits New Highs", "summary": "A brief summary of the article...", "publishDate": "2023-10-01T12:34:56Z", "createdAt": "2023-10-01T12:35:10Z", "language": "en", "images": [ "https://www.example.com/image1.jpg", "https://www.example.com/image2.jpg" ], "categories": ["markets"] } ``` **Response (includeUpdates: true):** ```json { "link": "https://www.example.com/article1", "source": "www.example.com", "title": "Stock Market Hits New Highs — Updated", "summary": "An updated summary of the article...", "publishDate": "2023-10-01T12:34:56Z", "createdAt": "2023-10-01T12:35:10Z", "revisedDate": "2023-10-02T08:00:00Z", "isUpdate": true, "language": "en", "images": [ "https://www.example.com/image1.jpg" ], "categories": ["markets"] } ``` --- ## Query Field-Level Filtering The `query` parameter for Raw Webhooks supports field-level filtering scoped to these fields only: - **`source`** — filter by article source domain - **`title`** — filter by content in the article title - **`summary`** — filter by content in the article summary **Examples:** ```plaintext query=title:Nvidia ``` Delivers articles where the title contains "Nvidia". ```plaintext query=summary:earnings +title:Tesla ``` Delivers articles where the summary mentions "earnings" and the title contains "Tesla". ```plaintext query=source:www.reuters.com -crypto ``` Delivers articles from Reuters, excluding those mentioning "crypto". See the [Advanced Query Building](https://docs.finlight.me/en/v2/advanced-query-building/#raw-websocket-query-fields) guide for the full query syntax reference. --- ## When to Use Raw Webhooks (GUIDE Decision Help) **Choose Raw when you:** - Need the lowest possible delivery latency - Are building a high-throughput pipeline where enrichment data is not required - Only need to filter by keywords, sources, or language - Want a leaner payload to reduce processing overhead on your end **Choose Enriched when you:** - Need company/ticker-level filtering (`tickers`, `countries`, `categories`) - Want sentiment scores, confidence values, or entity resolution in the payload - Need to include full article content or extracted entities via `includeContent` / `includeEntities` - Are building equity monitoring, earnings tracking, or sector-specific news feeds For full details on enriched webhook filtering options, see the [Filtering Criteria](https://docs.finlight.me/en/v2/webhooks/filtering/) guide. --- # Webhook Authentication - Secure Your Endpoints URL: https://docs.finlight.me/en/v2/webhooks/authentication/ finlight provides multiple authentication methods to secure your webhook deliveries. Every webhook includes signature validation by default, with optional additional authentication layers for enhanced security. finlight supports four authentication methods that can be used individually or in combination: ## None (NONE No Additional Auth) No additional authentication beyond the default signature validation. **When to Use:** - Testing and development environments - Internal endpoints behind secure networks - When signature validation provides sufficient security **Note:** Signature validation is still included with every webhook request regardless of this setting. --- ## X-Finlight-Key Header (FINLIGHT_KEY Custom Header) Sends your API key in a custom `X-Finlight-Key` header with each webhook request. **Configuration:** - Provide your API key during webhook setup - The key will be included in the `X-Finlight-Key` header **Implementation:** Your endpoint should validate the incoming header: ```javascript const finlightKey = req.headers['x-finlight-key'] if (finlightKey !== 'your-expected-api-key') { return res.status(401).send('Invalid API key') } ``` **Headers Sent:** ``` X-Finlight-Key: your-api-key-value X-Webhook-Signature: sha256=signature X-Webhook-Timestamp: 2024-01-15T10:30:00.000Z ``` --- ## Basic Authentication (BASIC Username/Password) HTTP Basic Authentication with username/password credentials. **Configuration:** - Set username and password during webhook setup - Credentials are base64-encoded and sent in the `Authorization` header **Implementation:** Your endpoint receives standard HTTP Basic Auth: ```javascript const auth = req.headers.authorization if (!auth || !auth.startsWith('Basic ')) { return res.status(401).send('Missing Basic Auth') } const credentials = Buffer.from(auth.slice(6), 'base64').toString() const [username, password] = credentials.split(':') if (username !== 'expected-user' || password !== 'expected-pass') { return res.status(401).send('Invalid credentials') } ``` **Headers Sent:** ``` Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ= X-Webhook-Signature: sha256=signature X-Webhook-Timestamp: 2024-01-15T10:30:00.000Z ``` --- ## Signature Validation (SIGNATURE Always Included) **Automatic Security:** Every webhook request includes signature validation regardless of your chosen authentication method. **How It Works:** 1. finlight generates a timestamp when sending the webhook 2. Creates a message by concatenating: `timestamp + '.' + payload` 3. Signs the message using HMAC-SHA256 with your webhook's secret key 4. Sends both signature and timestamp in headers **Headers Included:** ``` X-Webhook-Signature: sha256=computed-signature X-Webhook-Timestamp: 2024-01-15T10:30:00.000Z ``` **Signature Algorithm:** ``` message = timestamp + '.' + raw_request_body signature = HMAC-SHA256(message, webhook_secret) ``` When no `X-Webhook-Timestamp` header is present, the message is the raw body alone. Compare the result in constant time, and reject deliveries whose timestamp is more than five minutes old. > **Note:** > **The body must be the raw, unparsed request bytes.** Any middleware that > decodes and re-encodes the JSON before you read it changes the byte sequence > and invalidates the signature — this is the most common cause of verification > failures. Read the body as a raw string or buffer, verify it, and only then > parse it. ### Verify with an official client Every [client library](https://docs.finlight.me/en/v2/client-libraries/) ships a helper that performs the whole check for you: it accepts the `sha256=` prefix on the signature, compares in constant time, enforces the five-minute replay window, and returns the parsed article. It throws or returns an error when verification fails — always answer that with a `4xx` and never process the payload. **Verify a webhook:** ```typescript const app = express() app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => { try { const article = WebhookService.constructEvent( req.body.toString(), req.headers['x-webhook-signature'] as string, process.env.WEBHOOK_SECRET!, req.headers['x-webhook-timestamp'] as string, ) console.log('New article:', article.title) res.sendStatus(200) } catch (err) { console.error('Webhook verification failed:', err) res.sendStatus(400) } }) ``` ```python from flask import Flask, request from finlight_client import WebhookService, WebhookVerificationError app = Flask(__name__) @app.post("/webhook") def webhook(): try: article = WebhookService.construct_event( request.get_data(as_text=True), request.headers.get("X-Webhook-Signature", ""), os.environ["WEBHOOK_SECRET"], request.headers.get("X-Webhook-Timestamp"), ) except WebhookVerificationError: return "", 400 print("New article:", article.title) return "", 200 ``` ```go http.HandleFunc("/webhook", func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusBadRequest) return } article, err := finlight.ConstructWebhookEvent( body, r.Header.Get("X-Webhook-Signature"), os.Getenv("FINLIGHT_WEBHOOK_SECRET"), r.Header.Get("X-Webhook-Timestamp"), // "" if absent ) if err != nil { w.WriteHeader(http.StatusBadRequest) return } fmt.Println("new article:", article.Title) w.WriteHeader(http.StatusOK) }) ``` ```csharp app.MapPost("/webhooks/finlight", async (HttpRequest request) => { using var reader = new StreamReader(request.Body); var rawBody = await reader.ReadToEndAsync(); try { var article = FinlightWebhooks.ConstructEvent( rawBody, request.Headers["X-Webhook-Signature"]!, endpointSecret: "your-webhook-secret", request.Headers["X-Webhook-Timestamp"]); Console.WriteLine($"New article: {article.Title}"); return Results.Ok(); } catch (FinlightWebhookVerificationException) { return Results.BadRequest(); } }); ``` ```java // e.g. in a Spring controller @PostMapping("/webhook") public ResponseEntity onWebhook( @RequestBody String rawBody, @RequestHeader("X-Webhook-Signature") String signature, @RequestHeader(value = "X-Webhook-Timestamp", required = false) String timestamp) { try { Article article = WebhookService.constructEvent(rawBody, signature, webhookSecret, timestamp); log.info("New article: {}", article.title()); return ResponseEntity.ok().build(); } catch (WebhookVerificationException e) { return ResponseEntity.badRequest().build(); } } ``` ```php use Finlight\Exception\WebhookVerificationException; use Finlight\Service\WebhookService; try { $article = WebhookService::constructEvent( file_get_contents('php://input'), $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '', getenv('FINLIGHT_WEBHOOK_SECRET') ?: '', $_SERVER['HTTP_X_WEBHOOK_TIMESTAMP'] ?? null, ); } catch (WebhookVerificationException $e) { http_response_code(400); exit; } // Acknowledge fast, process asynchronously. http_response_code(200); ``` ```ruby # e.g. in a Rails controller def webhook article = Finlight::WebhookService.construct_event( request.raw_post, request.headers["X-Webhook-Signature"], ENV["WEBHOOK_SECRET"], request.headers["X-Webhook-Timestamp"] ) Rails.logger.info("New article: #{article.title}") head :ok rescue Finlight::WebhookVerificationError head :bad_request end ``` ```rust use finlight_client::construct_webhook_event; // raw_body: unmodified request body bytes // signature: X-Webhook-Signature header (with or without "sha256=" prefix) // timestamp: X-Webhook-Timestamp header, None if absent let article = construct_webhook_event( &raw_body, &signature, &std::env::var("FINLIGHT_WEBHOOK_SECRET")?, timestamp.as_deref(), )?; println!("new article: {}", article.title); ``` --- ## Security Best Practices (SECURITY Essential Guidelines) ### Timestamp Validation The `constructEvent` helpers above already enforce a five-minute replay window, so this is only needed if you verify signatures by hand: ```javascript function isTimestampValid(timestamp, toleranceSeconds = 300) { const now = Date.now() const requestTime = new Date(timestamp).getTime() const difference = Math.abs(now - requestTime) / 1000 return difference <= toleranceSeconds } ``` ### Secure Credential Storage - **Environment Variables**: Store all secrets in environment variables - **Secret Management**: Use AWS Secrets Manager, HashiCorp Vault, or similar - **Never Hard-Code**: Never commit secrets to version control - **Regular Rotation**: Update webhook secrets periodically --- For webhook setup guidance, see the [main webhooks documentation](https://docs.finlight.me/en/v2/webhooks/). For comprehensive testing, check the [webhook testing guide](https://docs.finlight.me/en/v2/webhooks/testing/). --- # Testing Webhooks - Dashboard Tools & Monitoring URL: https://docs.finlight.me/en/v2/webhooks/testing/ The finlight dashboard provides comprehensive testing and monitoring tools to ensure your webhook integration works reliably. Use these built-in features to validate, test, and debug your webhook endpoints. ## Dashboard Features Summary (SUMMARY) ### Key Dashboard Tools **Webhook List:** - View all your configured webhooks - See status (enabled/disabled) at a glance - Quick access to webhook details **Webhook Details Page:** - **Configuration tab** - View/edit webhook settings - **Call History tab** - See all delivery attempts - **Test Button** - Manual testing functionality **Call History Features:** - **Status filtering** - Show only successes or failures - **Detailed logs** - Click entries for full request/response data --- ## Webhook Details Dashboard (DASHBOARD Management Interface) Access your webhook management interface at [app.finlight.me/news-webhooks](https://app.finlight.me/news-webhooks) to view and manage all your webhooks. ### Accessing Webhook Details 1. **Navigate** to your webhook list in the dashboard 2. **Click** on the "Show" webhook button to view its details page 3. **View** comprehensive information about your webhook configuration and performance The webhook details page provides: - **Configuration Overview** - Current settings and filtering criteria - **Call History** - Complete log of all webhook attempts - **Test Controls** - Manual testing functionality - **Edit Controls** - Manual editing after creation --- ## Manual Testing (TESTING Test Button) ### Test Webhook Feature The dashboard includes a **"Test"** button that sends a sample payload to your endpoint: **How to Use:** 1. **Open** your webhook details page 2. **Click** the **"Test"** button on the top panel 3. **Wait** a few seconds for the test request to complete 4. **Review** the test results in the call history (maybe refresh the page) **What Happens:** - Sends a realistic sample payload to your configured endpoint - Uses your actual authentication settings - Includes proper signature validation headers - Records the test attempt in your call history **Test Payload:** The test sends a mock article event that follows the same structure as real webhook deliveries, allowing you to validate: - Endpoint accessibility and response - Authentication configuration - Payload processing logic - Error handling capabilities --- ## Call History & Monitoring (HISTORY Delivery Logs) ### Viewing Call History The webhook details page displays a comprehensive **call history** showing all delivery attempts: **Information Displayed:** - **Timestamp** - When the webhook was sent - **Status** - Success (2xx) or Failed (4xx/5xx) - **Response Code** - HTTP status code returned by your endpoint - **Response Time** - How long your endpoint took to respond - **Response** - The whole response (header and body) inside the dropdown content by clicking on "Show" ### Success vs Failed Requests **Successful Requests** (✅): - HTTP status codes 200-299 - Response received within timeout period - Proper acknowledgment from your endpoint **Failed Requests** (❌): - HTTP status codes 400-599 - Network timeouts or connection errors - Authentication failures - Invalid endpoint URLs --- ## Debugging with Dashboard (DEBUG Troubleshooting) ### Using Call History for Debugging The call history is your primary tool for diagnosing webhook issues: **Identifying Patterns:** 1. **Filter by status** - View only failed requests to identify problems 2. **Check timestamps** - Look for timing patterns in failures 3. **Review response codes** - Understand what your endpoint is returning 4. **Examine retry attempts** - See how many times delivery was attempted **Common Failure Indicators:** - **HTTP 401/403** - Authentication or authorization issues - **HTTP 404** - Incorrect endpoint URL - **HTTP 500** - Internal server errors in your application - **Timeouts** - Your endpoint is taking too long to respond - **Connection errors** - Network connectivity issues ### Detailed Error Information Click on any call history entry to see: - **Full request headers** sent to your endpoint - **Response headers** received from your endpoint - **Response body** content (if any) - **Exact timing** information - **Retry history** for failed attempts --- ## Endpoint Requirements (REQUIREMENTS Implementation Guidelines) ### Response Requirements Your webhook endpoint must: **HTTP Response:** - Return status codes **200-299** for successful processing - Respond within **5 seconds** to avoid timeouts - Accept **POST** requests with **JSON** payloads **Headers:** - Process `X-Webhook-Signature` for signature validation - Handle `X-Webhook-Timestamp` for replay attack prevention - Support your chosen authentication method headers --- For webhook setup guidance, see the [main webhooks documentation](https://docs.finlight.me/en/v2/webhooks/). For authentication details, check the [authentication guide](https://docs.finlight.me/en/v2/webhooks/authentication/). --- # Good to Know - Webhook Limitations & System Behavior URL: https://docs.finlight.me/en/v2/webhooks/good-to-know/ Understanding how finlight handles webhook errors, retries, and limitations helps you build more reliable integrations and manage your quota effectively. --- ## Error Handling & Retries (RETRIES System Behavior) ### Retry Logic When a webhook delivery fails, finlight automatically retries the request on a fixed, backed-off schedule: **Retry Schedule:** - **1st retry**: 10 minutes after the failed attempt - **2nd retry**: 30 minutes after the 1st retry fails - **3rd retry**: 60 minutes after the 2nd retry fails **Maximum Attempts:** - Total of **4 delivery attempts** per webhook event — the initial delivery plus 3 retries - Each retry uses the same payload and headers - All attempts are logged in your call history ### What Triggers Retries Retries occur for: - **Any non-2xx HTTP response** — including 3xx redirects, which are *not* followed - **Network timeouts** (5 second limit) - **Connection failures** (DNS errors, refused connections) - **SSL/TLS errors** (certificate issues) ### What Doesn't Trigger Retries No retries for: - **HTTP 2xx responses** (considered successful) - **HTTP 410 Gone** — this disables the webhook immediately (see below) - **Invalid webhook configuration** (malformed URLs) - **Disabled webhooks** --- ## Auto-Disable Protection (AUTO_DISABLE Failure Protection) ### Consecutive Failure Tracking finlight tracks consecutive webhook failures to protect your quota and prevent endless failed attempts. **How It Works:** 1. **Success Resets Counter** - Any successful delivery (HTTP 2xx) resets the failure counter to 0 2. **Failures Increment Counter** - Each failed delivery **attempt** increases the count — retries count individually, so a single event that exhausts all 4 attempts adds 4 to the counter 3. **Auto-Disable at 10** - After 10 failed attempts with no success in between, the webhook is automatically disabled The counter itself expires after **7 days** without a failure, so an endpoint that fails occasionally but never 10 times in a streak is never auto-disabled. ### Auto-Disable Behavior **When Auto-Disable Triggers:** - **10 failed delivery attempts** with no successful delivery in between (retries count individually) - **A single HTTP 410 Gone** response — disables immediately, with no retries (see below) - Webhook status changes from "enabled" to "disabled" - **No further webhook attempts** until manually re-enabled **How you are notified:** - We send you an **email** (typically within ~10 minutes of the webhook being disabled) - There is **no in-app notification** — in the dashboard, the webhook simply shows as `Disabled`, and its detail page explains why **Important Notes:** - Only failures **with no success in between** count toward auto-disable - **Any successful delivery** resets the counter to 0 - **Manual re-enabling required** - webhooks don't auto-enable - **All failure types** count (timeouts, non-2xx responses, connection and TLS errors) ### HTTP 410 Gone — immediate disable If your endpoint answers a delivery with **HTTP 410 Gone**, finlight treats that as "this endpoint is permanently gone": the webhook is disabled straight away, with no retries and without waiting for the failure counter to reach 10. Return 410 deliberately when you want to shut a webhook off from your side; return **5xx** if you want the delivery retried instead. ### Example Scenarios **Scenario 1: Counter Reset** ``` Attempt 1: Failed (counter = 1) Attempt 2: Failed (counter = 2) Attempt 3: Success (counter = 0) ← Reset! Attempt 4: Failed (counter = 1) ``` **Scenario 2: Auto-Disable** ``` 10 failed attempts, no success in between (counter = 10) → Webhook automatically disabled Note: these are attempts, not events. Retries count too, so ~3 events that each fail all 4 attempts are enough to reach 10. ``` --- ## Recovery & Re-enabling (RECOVERY Getting Back Online) ### Manual Re-enabling Process **Steps to Re-enable:** 1. **Identify root cause** using call history 2. **Fix endpoint issues** (authentication, URL, server errors) 3. **Re-enable the webhook** — press **Enable** on its detail page in the dashboard 4. **Test webhook manually** using dashboard test button 5. **Monitor initial deliveries** to confirm resolution > **Note:** > Webhooks created in the dashboard start **disabled** by default, so you can test your endpoint > before anything is delivered to it. Switch on **Activate immediately** in the creation wizard if > you want a new webhook to go live right away. While a webhook is disabled, matching articles are > **skipped, not queued** — they are not delivered retroactively when you enable it. ### Prevention Strategies **Avoid Auto-Disable:** - **Implement proper error handling** in your endpoint - **Return appropriate HTTP status codes** - **Monitor webhook health** proactively - **Set up alerting** for webhook failures - **Test changes** in development before production --- ## Quota Management (QUOTA Usage Tracking) You can view your usage on the dashboard on the graph. Keep in mind the usage is recorded delayed. ### Failed Requests Count Toward Quota **Important:** All webhook delivery attempts count toward your subscription quota, including failed deliveries. **What Counts:** - **Initial delivery attempts** - count toward quota - **All retry attempts** - each retry counts separately - **Failed deliveries** - still consume quota **What doesn't count:** - **Test webhook requests** sent from the dashboard - these do not consume your delivery quota. They are separately rate-limited (a handful per minute). **Quota Impact Example:** ``` 1 webhook event that fails all 4 attempts = 4 quota usage 1 webhook event with 1 successful delivery = 1 quota usage ``` ### Running out of quota pauses deliveries — it does not disable the webhook This is an important distinction, because the two states look different in the dashboard: - **Auto-disabled** (delivery failures): the webhook's status becomes `Disabled`. You re-enable it yourself once the endpoint is fixed. - **Quota exhausted**: the webhook's status **stays `Enabled`**, but every delivery is silently paused — no events reach your endpoint, and matching articles are skipped rather than queued. When your webhook quota runs out we send you an email, and the webhook's detail page in the dashboard shows a banner explaining that deliveries are paused. Deliveries resume when your quota resets, or immediately if you upgrade your plan. ### Managing Quota Efficiently **Best Practices:** - **Fix endpoint issues quickly** to minimize failed retries - **Monitor call history** for failure patterns - **Test thoroughly** before enabling webhooks in production - **Use proper error handling** to return appropriate status codes **Quota Protection:** The auto-disable feature helps prevent quota waste by stopping deliveries to consistently failing endpoints. --- For webhook setup guidance, see the [main webhooks documentation](https://docs.finlight.me/en/v2/webhooks/). For testing and debugging, check the [testing guide](https://docs.finlight.me/en/v2/webhooks/testing/). --- # MCP Server for AI Assistants URL: https://docs.finlight.me/en/v2/ai-assistants/ **Ask questions. Get answers. No code required.** Connect Claude Desktop or ChatGPT to finlight using MCP (Model Context Protocol) and access real-time financial news through natural conversation. Ask for news about specific companies, filter by sentiment, track market events - all without leaving your chat window or writing a single line of code. **MCP Server URL:** `https://mcp.finlight.me` --- ## Why Use This? (VALUE Benefits) Instead of checking multiple news sites, building dashboards, or writing scripts - just ask: > "Show me all negative sentiment news about NVIDIA from the last 24 hours" > "What's the latest on the EU tariff situation and which companies are mentioned?" > "Summarize all Reuters and Bloomberg coverage of the Fed meeting today" Your AI assistant queries finlight's database in real-time, filters by your criteria, and synthesizes the results. The answers are precise, sourced, and up-to-date - not hallucinated. --- ## Who Is This For? (AUDIENCE Use Cases) ### Financial Analysts & Portfolio Managers Stop tab-switching between news sites. Ask your AI assistant to monitor specific tickers, track sentiment shifts, or flag breaking news about your holdings. **Try asking:** > "What negative news has come out about companies in the semiconductor sector this week?" > "Find all news mentioning my watchlist: AAPL, MSFT, GOOGL, AMZN - sorted by most recent" ### Research Teams at Funds & Family Offices Use Claude as a research assistant that can pull and synthesize news from dozens of sources instantly. **Try asking:** > "Summarize today's coverage of the Federal Reserve meeting, grouped by topic" > "What are analysts saying about the impact of new regulations on fintech companies?" ### Quant Developers & Trading Teams You already use finlight's API programmatically. The AI connection lets you do ad-hoc research in natural language during your workflow - perfect for exploratory analysis before committing to building something. **Try asking:** > "Are there any breaking news items about companies on my watchlist in the last hour?" > "What's the sentiment distribution for Tesla news this quarter?" ### Financial Journalists & Content Creators Find trending stories, discover angles, and research topics faster than ever. **Try asking:** > "What are the top 5 most covered geopolitical stories in the last 6 hours?" > "Find contrarian takes on the latest Apple earnings report" ### Anyone Who Uses AI Daily If you already use Claude or ChatGPT as your daily work tool, you can now add financial news intelligence to your conversations. No API knowledge required - just ask questions in plain English. --- ## Connect Claude Desktop (CLAUDE Setup Guide) Claude Desktop connects directly to finlight using the MCP (Model Context Protocol) standard. Setup takes about 2 minutes. ### What You'll Need - **Claude Desktop app** installed on your computer ([Download here](https://claude.ai/download)) - **finlight API key** from your dashboard ([Get one here](https://app.finlight.me)) ### Step-by-Step Setup #### Step 1: Open Claude Desktop Settings 1. Launch **Claude Desktop** on your computer 2. Click on the **menu icon** (three lines or gear icon) 3. Select **Settings** 4. Navigate to the **MCP Servers** section #### Step 2: Add the finlight Server 1. Click **"Add Server"** or the **+** button 2. Enter the server URL: ``` https://mcp.finlight.me ``` 3. Click **Connect** or **Add** #### Step 3: Authorize with Your API Key 1. Claude will open a browser window 2. You'll see the finlight authorization page 3. Enter your **API key** from the [finlight dashboard](https://app.finlight.me) 4. Click **Authorize** 5. Return to Claude Desktop - you're now connected! --- ## Connect ChatGPT (CHATGPT Setup Guide) You can connect finlight to ChatGPT by creating a Custom GPT with an Action. ### What You'll Need - **ChatGPT Plus or Enterprise** subscription (required for Custom GPTs) - **finlight API key** from your dashboard ([Get one here](https://app.finlight.me)) ### Step-by-Step Setup #### Step 1: Create a New Custom GPT 1. Go to [chat.openai.com](https://chat.openai.com) 2. Click **Explore GPTs** in the sidebar 3. Click **Create** to start a new Custom GPT 4. Give it a name like **"Financial News Assistant"** #### Step 2: Configure the Action 1. In the **Configure** tab, scroll to **Actions** 2. Click **Create new action** 3. Set up authentication: - **Authentication Type**: OAuth - **Authorization URL**: `https://mcp.finlight.me/authorize` - **Token URL**: `https://mcp.finlight.me/token` - Leave other fields empty #### Step 3: Add the API Schema Paste this schema in the **Schema** section: ```yaml openapi: 3.1.0 info: title: finlight News API version: 1.0.0 servers: - url: https://mcp.finlight.me paths: /: post: operationId: searchNews summary: Search financial news articles requestBody: required: true content: application/json: schema: type: object properties: jsonrpc: type: string enum: ["2.0"] method: type: string params: type: object id: type: string responses: "200": description: News search results ``` #### Step 4: Save and Test 1. Click **Save** to create your Custom GPT 2. Open your new GPT 3. When prompted, authorize with your finlight API key 4. Start asking about financial news! --- ## What Can You Ask? (FEATURES Capabilities) Your AI assistant can search, filter, and analyze news using all of finlight's capabilities: | Capability | Example Prompt | |------------|----------------| | **Search by keyword** | "Find news about interest rate hikes" | | **Filter by ticker** | "What's the latest on NVDA and AMD?" | | **Filter by sentiment** | "Show me negative news about Boeing" | | **Search date ranges** | "News from the past 48 hours about Tesla" | | **Filter by source** | "What is Reuters reporting about the Fed?" | | **Filter by country** | "News about German automotive companies" | | **Get article details** | "Get the full content of this Reuters article" | | **Discover sources** | "What news sources are available?" | --- ## Example Prompts (EXAMPLES Try These) ### Morning Market Briefing > "Give me a summary of the most important financial news from the last 12 hours, focusing on US markets" ### Earnings Season Tracking > "Find all earnings announcements from tech companies this week. Highlight any surprises or guidance changes" ### Competitive Intelligence > "Compare news coverage of Microsoft and Google over the past month. What themes are emerging for each?" ### Risk Monitoring > "Show me any negative sentiment news about banks and financial institutions from today" ### Sector Research > "What's being written about the AI chip shortage? Which companies are mentioned most?" ### Event Analysis > "Summarize all coverage of the FOMC meeting from the past 24 hours. What are the key takeaways?" --- ## Troubleshooting (HELP Common Issues) ### "Connection Failed" Error - **Check your API key** - Make sure it's valid in your [finlight dashboard](https://app.finlight.me) - **Try reconnecting** - Remove the server and add it again - **Check your subscription** - Some features require a paid plan ### "Unauthorized" Error - Your API key may have expired or been revoked - Generate a new key in your dashboard and reconnect ### No Results Returned - Try broader search terms - Check the date range - very recent news may take a few minutes to appear - Verify the ticker symbols are correct (use standard symbols like AAPL, not "Apple") --- ## For Developers (DEVELOPERS Advanced) Want to integrate finlight into your own applications? Check out our [Developer Integration Guide](https://docs.finlight.me/en/v2/ai-assistants/developers/) for: - Direct HTTP API calls - TypeScript and Python examples - Full parameter reference - OAuth flow details - Error handling --- ## Get Started (START Next Steps) **Ready to connect?** 1. **[Get your API key](https://app.finlight.me)** - Free tier available 2. **Connect your AI assistant** - Follow the Claude or ChatGPT guide above 3. **Start asking questions** - Try the example prompts to see what's possible **Need help?** Visit our [Support page](https://docs.finlight.me/en/v2/support/) or check your subscription at [app.finlight.me](https://app.finlight.me). --- # MCP Server - Developer Integration URL: https://docs.finlight.me/en/v2/ai-assistants/developers/ This guide covers programmatic integration with the finlight MCP server. Use this to build custom AI applications, automate news retrieval, or integrate financial news into your existing systems. --- ## Server Information (INFO Endpoints) | Environment | URL | |-------------|-----| | Production | `https://mcp.finlight.me` | The server implements **MCP (Model Context Protocol)** via JSON-RPC 2.0 over HTTP. --- ## Authentication (AUTH API Key) All tool calls require authentication via Bearer token. Your finlight API key serves as the access token. ```bash Authorization: Bearer YOUR_API_KEY ``` For automated OAuth flows (like Claude Desktop), the server implements OAuth 2.0 with PKCE. See [OAuth Flow](#oauth-flow) for details. --- ## Quick Start (QUICKSTART Examples) ### Using cURL List available tools: ```bash curl -X POST https://mcp.finlight.me \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/list" }' ``` Search for articles: ```bash curl -X POST https://mcp.finlight.me \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "search_articles", "arguments": { "query": "NVIDIA earnings", "tickers": ["NVDA"], "pageSize": 10 } } }' ``` ### Using TypeScript ```typescript const transport = new StreamableHTTPClientTransport( new URL("https://mcp.finlight.me"), { requestInit: { headers: { Authorization: `Bearer ${process.env.FINLIGHT_API_KEY}`, }, }, } ); const client = new Client({ name: "my-app", version: "1.0.0", }); await client.connect(transport); // List available tools const tools = await client.listTools(); console.log("Available tools:", tools); // Search articles const result = await client.callTool({ name: "search_articles", arguments: { query: "Federal Reserve interest rates", from: "2024-01-01", pageSize: 5, }, }); console.log("Articles:", result); ``` ### Using Python ```python API_KEY = "your-api-key" MCP_URL = "https://mcp.finlight.me" def mcp_request(method: str, params: dict = None): response = requests.post( MCP_URL, headers={ "Content-Type": "application/json", "Authorization": f"Bearer {API_KEY}", }, json={ "jsonrpc": "2.0", "id": 1, "method": method, "params": params or {}, }, ) return response.json() # List available tools tools = mcp_request("tools/list") print("Available tools:", json.dumps(tools, indent=2)) # Search articles articles = mcp_request("tools/call", { "name": "search_articles", "arguments": { "query": "Tesla Model 3", "tickers": ["TSLA"], "from": "2024-01-01", "pageSize": 10, }, }) print("Articles:", json.dumps(articles, indent=2)) ``` --- ## Available Tools (TOOLS Reference) ### search_articles Search for financial news articles with advanced filtering and sentiment analysis. **Parameters:** | Parameter | Type | Description | |-----------|------|-------------| | `query` | string | Search query with boolean operators (AND, OR, NOT) and field filters (`ticker:AAPL`, `source:reuters.com`) | | `tickers` | string[] | Filter by stock ticker symbols (e.g., `["AAPL", "NVDA"]`) | | `sources` | string[] | Limit to specific news source domains | | `optInSources` | string[] | Add sources to the default set (instead of replacing) | | `excludeSources` | string[] | Exclude specific sources from results | | `countries` | string[] | Filter by ISO 3166-1 alpha-2 country codes | | `from` | string | Start date (YYYY-MM-DD or ISO 8601) | | `to` | string | End date (YYYY-MM-DD or ISO 8601) | | `language` | string | Language code (default: "en") | | `includeContent` | boolean | Include full article text (requires subscription) | | `includeEntities` | boolean | Include tagged company entities | | `excludeEmptyContent` | boolean | Skip articles without content | | `order` | "ASC" \| "DESC" | Sort order (default: DESC = newest first) | | `orderBy` | "publishDate" \| "createdAt" \| "revisedDate" | Sort field — `revisedDate` sorts by most recent revision date | | `pageSize` | number | Results per page (1-100, default: 20) | | `page` | number | Page number (default: 1) | **Example Request:** ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "search_articles", "arguments": { "query": "earnings report", "tickers": ["AAPL", "MSFT"], "from": "2024-01-01", "to": "2024-03-31", "language": "en", "pageSize": 20 } } } ``` **Example Response:** ```json { "jsonrpc": "2.0", "result": { "content": [{ "type": "text", "text": "{\"articles\":[{\"title\":\"Apple Reports Record Q1...\",\"summary\":\"...\",\"link\":\"https://...\",\"publishDate\":\"2024-02-01T16:30:00Z\",\"source\":\"www.reuters.com\",\"sentiment\":\"positive\",\"sentimentConfidence\":0.92}],\"totalResults\":847,\"page\":1,\"pageSize\":20}" }] }, "id": 1 } ``` --- ### get_article_by_link Retrieve a specific article by its URL. **Parameters:** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `link` | string | Yes | The full URL of the article | | `includeContent` | boolean | No | Include full article text | | `includeEntities` | boolean | No | Include tagged company entities | **Example Request:** ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "get_article_by_link", "arguments": { "link": "https://www.reuters.com/technology/example-article", "includeContent": true, "includeEntities": true } } } ``` --- ### list_sources Get all available news sources with metadata. **Parameters:** None **Example Request:** ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "list_sources", "arguments": {} } } ``` **Response includes:** - `domain` - Source website domain - `isDefaultSource` - Whether included in default searches - `isContentAvailable` - Whether full content retrieval is supported --- ## MCP Protocol Methods (PROTOCOL JSON-RPC) The server implements these MCP protocol methods: | Method | Description | |--------|-------------| | `initialize` | Initialize the MCP session | | `notifications/initialized` | Confirm initialization complete | | `tools/list` | List available tools and their schemas | | `tools/call` | Execute a tool with arguments | | `ping` | Health check | **Initialize Example:** ```json { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": { "name": "my-client", "version": "1.0.0" } } } ``` **Response:** ```json { "jsonrpc": "2.0", "result": { "protocolVersion": "2024-11-05", "capabilities": { "tools": {} }, "serverInfo": { "name": "finlight-news-api", "version": "1.0.0" } }, "id": 1 } ``` --- ## OAuth Flow (OAUTH Authentication) For clients that support OAuth (like Claude Desktop), the server implements OAuth 2.0 with PKCE. ### Endpoints | Endpoint | Method | Description | |----------|--------|-------------| | `/.well-known/oauth-protected-resource` | GET | Protected resource metadata | | `/.well-known/oauth-authorization-server` | GET | Authorization server metadata | | `/register` | POST | Dynamic client registration | | `/authorize` | GET | Authorization page | | `/authorize/submit` | POST | Process authorization | | `/token` | POST | Exchange code for token | ### Flow Overview ``` 1. Client discovers OAuth endpoints via .well-known 2. Client optionally registers via /register 3. Client redirects user to /authorize with PKCE challenge 4. User enters API key and submits 5. Server redirects back with authorization code 6. Client exchanges code + verifier for access token 7. Client uses access token as Bearer token for API calls ``` ### Security Features - **PKCE Required** - Prevents authorization code interception - **Self-Encrypted Codes** - AES-256-GCM encrypted, stateless - **Short-Lived Codes** - 120 second expiration - **Redirect URI Validation** - Codes bound to original URI --- ## Error Handling (ERRORS Troubleshooting) ### JSON-RPC Error Codes | Code | Message | Description | |------|---------|-------------| | -32700 | Parse error | Invalid JSON | | -32600 | Invalid Request | Missing jsonrpc or method | | -32601 | Method not found | Unknown method | | -32602 | Invalid params | Invalid tool parameters | | -32001 | Unauthorized | Missing or invalid API key | | -32603 | Internal error | Server-side error | ### API Error Responses Tool calls that fail return an error structure: ```json { "jsonrpc": "2.0", "result": { "isError": true, "content": [{ "type": "text", "text": "Error: Invalid API key" }] }, "id": 1 } ``` **Common HTTP-level errors:** | Status | Description | |--------|-------------| | 401 | Invalid API key | | 403 | Subscription doesn't allow this operation | | 429 | Rate limit exceeded | | 400 | Validation error | --- ## Rate Limits (LIMITS Quotas) Rate limits depend on your finlight subscription plan. When limits are exceeded, the API returns a `429` status code. Check your current usage and limits at [app.finlight.me](https://app.finlight.me). --- ## Support (SUPPORT Help) - **Documentation**: [docs.finlight.me](https://docs.finlight.me) - **Dashboard**: [app.finlight.me](https://app.finlight.me) - **Support**: [Contact us](https://docs.finlight.me/en/v2/support/) --- # Advanced Query Building URL: https://docs.finlight.me/en/v2/advanced-query-building/ When working with the finlight.me API, you have the power to retrieve exactly the data you need through advanced query building techniques. This guide walks you through complex filtering, sorting, and pagination methods to help you optimize your data retrieval process. Quickly access the API and test your queries using our [Dashboard - API Tester](https://app.finlight.me/news-api). --- ## Language and Multilingual Coverage finlight indexes news in **many languages**, but every request is filtered to **one** language. The `language` parameter defaults to **`en`**, so if you don't set it you receive **English articles only** — content in any other language is silently excluded. > **Important:** `language` defaults to `en`. A request without `language` returns **only English** results. Articles published in other languages (for example many Chinese-language outlets, `zh`) are **not** returned unless you explicitly request that language. ### How it works - **Article-level, exact match.** `language` filters on each article's [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1) code as an exact match. `language=en` returns only `en` articles and never `de`, `zh`, etc. - **One language per request.** `language` takes a **single** value — arrays/comma lists are not supported and there is **no "all languages" option**. To cover several languages, send **one request per language** and merge the results. - **Sources can be multilingual.** A single source may publish in more than one language; the filter selects articles by their language, not the source. An outlet's non-English articles only appear when you request that language. ### Examples **Default (English only) — equivalent:** ```plaintext query=Alibaba query=Alibaba&language=en ``` **Chinese-language coverage:** ```plaintext query=Alibaba&language=zh ``` **Cover English + Chinese — two requests, then merge:** ```plaintext query=Alibaba&language=en query=Alibaba&language=zh ``` > **Tip:** Use [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1) codes (`en`, `de`, `fr`, `zh`, …). finlight's default source set spans many languages — English is just the default filter, not the limit of coverage. --- ## Query Filtering The `query` parameter enables flexible keyword-based logic **and field-level precision**. You can now **target specific fields** like `ticker`, `exchange`, `isin`, `source`, `openfigi` and more. ### Basic Keyword Usage **Single keyword:** ```plaintext query=Nvidia stock ``` **Exact phrase:** Wrap phrases in double quotes to search for exact matches. ```plaintext query="Elon Musk" ``` ### Inclusion / Exclusion with Operators **Force inclusion (+) and exclusion (-):** Use `+` to **require/inclusion**, and `-` to **exclude** terms or field-specific values. ```plaintext query=stock +market -google ``` This will return articles that contain "stock" and "market", but exclude any that mention "google". --- ## Field-Level Filtering > **Note:** This is a powerful new feature that allows you to filter results based on specific fields directly within the `query` parameter. You can now query **specific fields** directly using the `field:value` syntax also on the `query` parameter. This allows for more precise and complex queries, enabling you to filter results based on specific attributes like ticker symbols, exchanges, ISINs, sources, and more. > **✨ New:** Use wildcard `*` with `source`, `ticker`, and `exchange` fields to match all values (e.g., `source:*`, `ticker:*`, `exchange:*`). ### Supported Fields - `ticker` (supports wildcard `*` and vendor ticker notations — see **Ticker Notation Support** below) - `isin` - `title` - `summary` - `content` - `openfigi` - `exchange` (supports wildcard `*`) - All exchanges are MIC (Market identifier codes) standards. Supported codes include: `ASEX`, `BVCA`, `BVMF`, `DSMD`, `HSTC`, `XSTC`, `MISX`, `NEOE`, `PFTS`, `ROCO`, `XADS`, `XAMM`, `XAMS`, `XASX`, `XBAH`, `XBEL`, `XBEY`, `XBKK`, `XBOG`, `XBOM`, `XBOT`, `XBRA`, `XBRU`, `XBSE`, `XBUD`, `XBUE`, `XBUL`, `XCAS`, `XCNQ`, `XCOL`, `XCSE`, `XCYS`, `XDAR`, `XDFM`, `XDHA`, `XDUS`, `XETR`, `XFKA`, `XFRA`, `XGHA`, `XHAM`, `XHEL`, `XHKG`, `XICE`, `XIDX`, `XIST`, `XJAM`, `XJSE`, `XKAR`, `XKAZ`, `XKLS`, `XKOR`, `XKUW`, `XLIM`, `XLIS`, `XLIT`, `XLJS`, `XLUS`, `XLUX`, `XMAL`, `XMAU`, `XMEX`, `XMIL`, `XMSW`, `XMUN`, `XNAI`, `XNAM`, `XNAS`, `XNGM`, `XNGO`, `XNSA`, `XNSE`, `XNYS`, `XASE`, `XOSL`, `XPAR`, `XPHS`, `XPRA`, `XRIS`, `XSAP`, `XSAU`, `XSES`, `XSCA`, `XSGO`, `XSHE`, `XSHG`, `XKRX`, `XSTU`, `XSWX`, `XTAE`, `XTAI`, `XTAL`, `XTSE`, `XTSX`, `XTUN`, `XUBS`, `XUGA`, `XWAR`, `XWBO`, `XZAG`, `XZIM`, `XSTO`, `OTCM`, `BMEX`, `XDUB`, `XJPX`, `BCXE`, `XPAE`, `XLON`, `XMUS`, `XNZE`, `XCAI`, `XBRV` - `country` - Filter by the countries an article is about, using [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country codes (e.g., `US`, `GB`, `DE`, `JP`, `CN`, `FR`, `CA`, `AU`, `IN`, `BR`, etc.). This matches the article's `countries` field, not the publisher's country, a company's domicile, or a listing market. - `category` - Filter by article category. Possible values: `markets`, `economy`, `business`, `politics`, `geopolitics`, `regulation`, `technology`, `energy`, `commodities`, `crypto`, `health`, `climate`, `security` - `source` (supports wildcard `*`) - [View all available sources in the API documentation](https://docs.finlight.me/v2/rest-endpoints/#get-all-sources) ### Ticker Notation Support > **✨ New:** You don't need to guess the right ticker format — common vendor notations are recognized automatically. Every platform writes tickers differently, so the API understands the most common notations out of the box: | Notation | Examples | |---|---| | Plain ticker symbol | `ticker:000660`, `ticker:AAPL` | | Yahoo Finance / Reuters dot suffix | `ticker:000660.KS`, `ticker:7203.T`, `ticker:SAP.DE`, `ticker:0700.HK` | | ISO country suffix | `ticker:000660.KR`, `ticker:NVDA.US` | | Google Finance / TradingView prefix | `ticker:KRX:000660`, `ticker:NASDAQ:AAPL`, `ticker:TYO:7203` | | US share-class variants | `ticker:BRK-B`, `ticker:BRK/B` (same as `ticker:BRK.B`) | | Lowercase input | `ticker:aapl` | The same notations work in the structured `tickers` request parameter (e.g. `tickers=["000660.KS", "KRX:005930"]`). **Good to know:** - Exchange-qualified notations pin a ticker to its market and disambiguate colliding symbols: bare `ticker:TM` matches any company with symbol `TM` on any exchange, while `ticker:TM.US` targets the US listing specifically. - The ticker and exchange always refer to **the same company** — a match is never assembled from two different companies. - US share-class tickers like `ticker:BRK.B`, `ticker:PBR.A` or `ticker:REI.UN` match exactly as typed — class letters are never mistaken for exchange suffixes. - `exchange:` values are flexible too: common exchange names like `exchange:KOSDAQ` or `exchange:NASDAQ` work alongside the MIC codes listed above. - Unknown suffixes or prefixes (e.g. `ticker:FOO.XX`) match literally. - Bloomberg's space notation (`000660 KS Equity`) is **not** supported — use one of the notations above. **Examples:** ```plaintext query=ticker:000660.KR query=ticker:KRX:000660 AND earnings query=(ticker:005930.KS OR ticker:000660.KS) -source:finance.yahoo.com query=ticker:NVDA.US AND category:technology ``` ### Wildcard Support The wildcard `*` allows you to explicitly include **all** sources, tickers, or exchanges in your query. This is particularly useful when you want to ensure broad coverage or when combining with other filters. **Examples:** ```plaintext query=source:* ``` Returns articles from all available sources. ```plaintext query=ticker:* country:US ``` Returns articles about any ticker for US companies. ```plaintext query=exchange:* -crypto ``` Returns articles from all exchanges, excluding cryptocurrency content. ### Field Filter Examples Try it out in the [API Tester](https://app.finlight.me/news-api) to see how it works and create your own complex queries easily. **Filter by exact source:** ```plaintext query=source:www.some-source.de ``` **Exclude a source:** ```plaintext query=-source:www.some-source.de ``` **Require specific ticker and exclude some source:** ```plaintext query=ticker:AAPL -source:www.some-source.de ``` **Find results where content mentions "earnings" and the exchange is NASDAQ:** ```plaintext query=content:earnings exchange:nasdaq ``` **Filter by articles about a specific country:** ```plaintext query=country:US ``` **Find news about Germany, excluding Schulden:** ```plaintext query=country:DE -Schulden ``` **Combine country and ticker filtering:** ```plaintext query=country:US ticker:NVD ``` **Combine field filtering with general search:** ```plaintext query="quarterly report" source:www.some-source.com -crypto ``` --- ## Boolean Operators > Note: Words are by default AND joined, you dont need to use AND explicitly unless you want to combine with OR or NOT. **AND / OR / NOT logic is fully supported:** ```plaintext query=stock AND google query=amazon OR google query=market AND NOT bitcoin ``` **Use parentheses for grouping:** Combine logical expressions for advanced filtering. ```plaintext query=("Elon Musk") AND (twitter OR tesla) ``` **Combine with wildcards for powerful queries:** ```plaintext query=ticker:* AND (country:US OR country:GB) -crypto query=source:* exchange:XNAS ``` ## 💡 Tips for Power Users - Field filters support `+` and `-` for required and excluded values. - **Wildcard `*`** can be used with `source`, `ticker`, and `exchange` fields to match all values. - You can **combine multiple fields and keywords** for highly targeted queries. - Boolean operators like `AND`, `OR`, and `NOT` are **case-insensitive**. - Parentheses `()` help **control precedence** in complex queries. - Use double quotes `"` around multi-word phrases to avoid partial matches. --- ## Conclusion - Combine Everything Example: Want news about Tesla (ticker:TSLA), from trusted sources, not about crypto? ```plaintext query=+ticker:TSLA -crypto AND (+source:www.bloomberg.com OR +source:www.reuters.com) ``` Example: Want news about Tesla (ticker:TSLA) or Apple (ticker:AAPL) from Bloomberg? ```plaintext query=source:www.bloomberg.com AND ticker:TSLA OR source:www.bloomberg.com AND ticker:APPL ``` Example: Want US-focused news that involves NASDAQ-listed companies, excluding cryptocurrency content? ```plaintext query=country:US exchange:XNAS -crypto ``` Example: Want earnings news focused on Germany, France, or the UK? ```plaintext query=earnings AND (country:DE OR country:FR OR country:GB) ``` Example: Want all ticker-related news from all sources, excluding crypto? ```plaintext query=ticker:* source:* -crypto ``` Try it out in the [API Tester](https://app.finlight.me/news-api) to see how it works and create your own complex queries easily. --- ## Raw WebSocket Query Fields The [Raw WebSocket](https://docs.finlight.me/en/v2/raw-websocket-subscribe/) supports a **subset** of field-level filters tailored to its simplified data model. Unlike the Enhanced WebSocket and REST API, the Raw WebSocket does not support ticker, exchange, or company-related field filters. ### Supported Fields - **`source`** - Filter by article source domain - **`title`** - Filter by article title content - **`summary`** - Filter by article summary content ### Examples **Filter by title content:** ```plaintext query=title:Nvidia ``` **Combine title and summary filters:** ```plaintext query=summary:earnings +title:Tesla ``` **Filter by source with keyword exclusion:** ```plaintext query=source:www.reuters.com -crypto ``` **Combine multiple field filters with boolean operators:** ```plaintext query=title:Apple AND summary:revenue ``` > **Note:** The standard query operators (`+`, `-`, `AND`, `OR`, `NOT`, parentheses, and double quotes) all work with Raw WebSocket field filters. --- ## Need Help? If you ever feel stuck, have a question, or see room for improvement, don’t hesitate to reach out. We look forward to hearing from you and supporting your success with the finlight.me API. --- # Client Libraries URL: https://docs.finlight.me/en/v2/client-libraries/ finlight publishes eight official client libraries. Each one wraps the same REST, WebSocket and webhook surface documented in the rest of these pages, so you can pick the one that matches your stack instead of hand-rolling HTTP calls. | Language | Package | Requires | Streaming | | ----------------------- | ------------------------------------------ | ----------- | --------- | | TypeScript / JavaScript | `finlight-client` (npm) | Node.js | Yes | | Python | `finlight-client` (PyPI) | Python 3.7+ | Yes | | Go | `github.com/callbk/finlight-client-go` | Go 1.23+ | Yes | | .NET / C# | `Finlight.Client` (NuGet) | .NET 8+ | Yes | | Java / Kotlin | `me.finlight:finlight-client` (Maven) | Java 17+ | Yes | | PHP | `finlight/client` (Packagist) | PHP 8.1+ | No | | Ruby | `finlight-client` (RubyGems) | Ruby 3.2+ | Yes | | Rust | `finlight-client` (crates.io) | Rust 1.85+ | Yes | --- ## What every client gives you The libraries are built to the same specification, so switching languages does not change the concepts you work with: - **REST**: search articles, fetch a single article by link, and list available sources — see [Endpoints](https://docs.finlight.me/en/v2/rest-endpoints/). - **Real-time streaming**: both the enhanced and the raw WebSocket feed, surfaced as the idiomatic stream type of the language (async iterators, channels, `Stream`s). Reconnects, the ping/pong keepalive and proactive connection rotation are handled for you — see [WebSocket Basics](https://docs.finlight.me/en/v2/websocket-basics/). - **Resilience**: retries with exponential backoff on `429` and `5xx` responses, so transient failures and [rate limits](https://docs.finlight.me/en/v2/rate-limits/) do not surface as errors in your code. - **Webhook verification**: HMAC-SHA256 signature checking with replay protection, matching [Webhook Authentication](https://docs.finlight.me/en/v2/webhooks/authentication/). - **Authentication**: you pass your API key to the constructor and the client sends it as the `X-API-KEY` header on every request. > **Note:** > The one deliberate exception is the PHP client, which does not implement > WebSocket streaming — PHP's request/response model is a poor fit for a > long-lived connection. Use [webhooks](https://docs.finlight.me/en/v2/webhooks/) for push delivery into a > PHP application. Nothing in the libraries is privileged: everything they do is available over plain HTTP and WebSocket, so cURL or any HTTP client remains a fully supported option. --- ## Install Every client reads your API key from the constructor and sends it as the `X-API-KEY` header. Grab a key in the [finlight Dashboard](https://app.finlight.me). **Install:** **TypeScript:** ```bash # npm — also published to JSR as @finlight/client npm install finlight-client ``` **Python:** ```bash pip install finlight-client ``` **Go:** ```bash go get github.com/callbk/finlight-client-go ``` **C#:** ```bash dotnet add package Finlight.Client ``` **Java:** ```kotlin // build.gradle.kts dependencies { implementation("me.finlight:finlight-client:0.1.0") } ``` **PHP:** ```bash # Guzzle is picked up automatically when installed; # any PSR-18 HTTP client works. composer require finlight/client ``` **Ruby:** ```bash gem install finlight-client ``` **Rust:** ```bash cargo add finlight-client tokio futures-util ``` If you build with Maven rather than Gradle, declare the same coordinate: ```xml me.finlight finlight-client 0.1.0 ``` ## Source repositories Every client is developed in the open under the MIT license. Issues and pull requests are welcome. - **TypeScript / JavaScript** — [jubeiargh/finlight-client](https://github.com/jubeiargh/finlight-client) - **Python** — [jubeiargh/finlight-client-py](https://github.com/jubeiargh/finlight-client-py) - **Go** — [callbk/finlight-client-go](https://github.com/callbk/finlight-client-go) - **.NET / C#** — [callbk/finlight-client-dotnet](https://github.com/callbk/finlight-client-dotnet) - **Java / Kotlin** — [callbk/finlight-client-java](https://github.com/callbk/finlight-client-java) - **PHP** — [callbk/finlight-client-php](https://github.com/callbk/finlight-client-php) - **Ruby** — [callbk/finlight-client-ruby](https://github.com/callbk/finlight-client-ruby) - **Rust** — [callbk/finlight-client-rust](https://github.com/callbk/finlight-client-rust) (API docs on [docs.rs](https://docs.rs/finlight-client)) ## What's next? - Make your first call with the [Quickstart](https://docs.finlight.me/en/v2/) - Browse the full [REST endpoint reference](https://docs.finlight.me/en/v2/rest-endpoints/) - Learn the query syntax in [Advanced Query Building](https://docs.finlight.me/en/v2/advanced-query-building/) - Stream articles in real time with the [WebSocket Quickstart](https://docs.finlight.me/en/v2/websocket-quickstart/) - Receive pushed articles via [Webhooks](https://docs.finlight.me/en/v2/webhooks/) - Found a bug or want a language that is missing? Reach out via [Support](https://docs.finlight.me/en/v2/support/) --- # Support and Contact Information URL: https://docs.finlight.me/en/v2/support/ Building on the finlight.me API means you’re never working alone. We’re here to help you along the way, whether you have a quick question, need technical guidance, or want to share ideas for new features. We offer multiple channels to ensure you can always find the assistance you need. --- ## Support Channels **Discord** Join our [Discord community](https://discord.com/invite/XUs9JYZd24) to connect with fellow developers and the finlight team in real-time. It’s a great place to: - Ask quick questions and receive instant feedback. - Share your integration experiences. - Learn from community best practices and code examples. **Email** For more in-depth inquiries or specific requests, reach out to us at [support@finlight.me](mailto:support@finlight.me). Our support team is happy to assist with: - Troubleshooting integration issues. - Providing detailed explanations of API features. - Addressing account-related questions or concerns. --- ## Feedback Your feedback is invaluable in helping us improve and expand the finlight.me API. We encourage you to share: - **Feature requests**: Tell us what functionalities or data you’d like to see next. - **Bug reports**: Alert us to any issues you encounter so we can fix them quickly. - **Suggestions & Ideas**: Have a unique use case or integration scenario? Let us know! By actively participating and providing feedback, you play a vital role in shaping the future of the finlight.me API. We’re committed to continually enhancing our platform to better serve your needs, and your input helps guide our roadmap. --- If you ever feel stuck, have a question, or see room for improvement, don’t hesitate to reach out. We look forward to hearing from you and supporting your success with the finlight.me API.