Developer docs
The raw contract first: exact requests, response shapes, queue behavior, and runnable list loops.
Checking key options…
Quickstart
- Sign in to choose a key, or replace bmi_YOUR_KEY in these examples.
- Send Authorization: Bearer bmi_YOUR_KEY to a search endpoint.
- Read 200 for the answer or 202 for the job and Retry-After.
Revoking a key takes effect within seconds. A request already reaching an edge server may still complete.
Lookups without a progress stream return a completed answer or a queued job within 30 seconds of request arrival.
curl -X POST https://bmiapi.com/api/v1/title-search \
-H "Authorization: Bearer bmi_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{"title":"STAND BY ME"}'Sign in to choose a key, or replace bmi_YOUR_KEY in these examples.
Endpoints and request fields
All search bodies are JSON. A secondary filter is sent with its value as a pair. Defaults are searchDatabase: Songview, viewCount: 20, pageNumber: 1, and dedupe: true.
| Endpoint | Body or path |
|---|---|
| POST /api/v1/title-search | title (string), secondaryFilter, secondaryValue, searchDatabase, viewCount (20|50|100), pageNumber (integer), dedupe (boolean) |
| POST /api/v1/writer-search | writerComposerName (string), catalog: { partId, partIdSub, partCae } from a result's catalogQuery, plus pageNumber and viewCount up to 100 |
| POST /api/v1/publisher-search | publisherName (string), catalog: { partId, partIdSub, partCae } from a result's catalogQuery, plus pageNumber and viewCount up to 100 |
| POST /api/v1/performer-search | performerName (string), plus the shared optional fields |
| POST /api/v1/work-id-search | bmiWorkId (string), searchDatabase, viewCount, pageNumber, dedupe |
| POST /api/v1/iswc-search | iswc (string), searchDatabase, viewCount, pageNumber, dedupe |
| GET /api/v1/jobs/{id} | id path parameter; optional claim query parameter from pollUrl |
A catalog request without viewCount uses 50, the canonical BMI page size. Optional headers: Idempotency-Key and Prefer: respond-async. Add ?refresh=true to skip a saved answer and ask BMI now (one live lookup).
Full response shape
A successful search envelope always keeps these fields. A value is null when Songview does not list it; arrays can be empty when there are no matches. The example below is a schema fixture.
- resultFamily
- works | writers | publishers | performers · The returned row family, also present in data.
metadata. - meta
- object · apiVersion (v1), requestId, jobId, cached, and durationMs are required.
- meta.
cached - boolean · true for a saved answer; false for a live lookup.
- meta.
requestId - string · The required request identifier.
- data.
metadata - object · searchType, primaryFilter, resultFamily, primaryValue, secondaryFilter, secondaryValue, searchDatabase, viewCount, pageNumber, dedupeApplied, rawSearchContext, and encodedSearchContext.
- data.
results - array · Work, writer, publisher, or performer rows. Empty means no match.
- pagination
- object · pageNumber, viewCount, totalPages, totalResults, totalResultsIsLowerBound, hasNextPage, hasPreviousPage. Only totals may be null when Songview does not expose them.
- warnings
- string[] · Parse, normalization, or missing-section notes; never silently discarded.
- querySuggestions
- array · route, input, rules, and basis. Suggestions are never run automatically.
Work rows
Work identifiers are workTitle, bmiWorkId, songViewStatus, iswc, and ascapWorkId. proShares contains organization, percentControlled (registry percent text), workId, and note. writers.
Entity families
resultFamily is works, writers, publishers, or performers, also repeated in data.
{
"resultFamily": "works",
"data": {
"metadata": {
"resultFamily": "works",
"searchType": "Title",
"primaryFilter": "Title",
"primaryValue": "Stop",
"secondaryFilter": null,
"secondaryValue": null,
"searchDatabase": "Songview",
"pageNumber": 1,
"viewCount": 20,
"dedupeApplied": true,
"rawSearchContext": null,
"encodedSearchContext": null
},
"results": [
{
"workTitle": "STOP",
"bmiWorkId": "123",
"songViewStatus": "Reconciled",
"iswc": "T0701420714",
"ascapWorkId": "490322031",
"alternateTitles": [
"STOP AND SMELL THE ROSES"
],
"derived": {
"listedTotalPercent": 100,
"unlistedPercent": 0,
"societies": [],
"shareTotals": null
},
"awards": [],
"proShares": [
{
"organization": "BMI",
"percentControlled": "50%",
"workId": "123",
"note": null
},
{
"organization": "ASCAP",
"percentControlled": "50%",
"workId": "490322031",
"note": null
}
],
"writers": {
"percentBreakdown": [
{
"organization": "BMI",
"percent": "50%",
"note": null
}
],
"contributors": [
{
"name": "DAVIS MAC",
"affiliation": "BMI",
"ipiNumber": "782249809",
"ipiNameNumber": "00782249809",
"catalog": null,
"isAffiliatedWithBmi": true
}
]
},
"performers": {
"percentBreakdown": [],
"values": {
"raw": [],
"deduped": []
}
},
"publishers": {
"percentBreakdown": [],
"entries": [
{
"name": "SONG PUBLISHING",
"affiliation": "BMI",
"ipiNumber": "1",
"ipiNameNumber": "00000000001",
"isAffiliatedWithBmi": true,
"catalog": null,
"contactInfo": null,
"notes": []
}
],
"hasOtherNonAscapOrBmiPublishers": null,
"otherPublishersNotice": "Other Participating Publishers"
}
}
]
},
"pagination": {
"pageNumber": 1,
"viewCount": 20,
"totalPages": 1,
"totalResults": 1,
"totalResultsIsLowerBound": false,
"hasNextPage": false,
"hasPreviousPage": false,
"resultsOnPage": 0,
"summary": ""
},
"warnings": [
"value-unknown: publishers.hasOtherNonAscapOrBmiPublishers is null for 1 work(s) because BMI printed a newer other-publishers label (see publishers.otherPublishersNotice) instead of \"Other Non-ASCAP and Non-BMI Publishers\", and the newer label does not say whether those publishers belong to ASCAP or BMI. BMI Work IDs: 123"
],
"querySuggestions": [],
"meta": {
"apiVersion": "v1",
"requestId": "fixture-request-success",
"jobId": "fixture-job-success",
"cached": false,
"durationMs": 1240
}
}202 Accepted and polling
A queued live lookup is durable. Honor Retry-After, then call the returned poll URL. Polls are free and have a separate limit of 120 per minute per job.
HTTP/1.1 202 Accepted
Retry-After: 3
Content-Type: application/json
{
"jobId": "job_example",
"status": "queued",
"pollUrl": "https://bmiapi.com/api/v1/jobs/job_example?claim=EXAMPLE",
"retryAfterSeconds": 3,
"queuePosition": 2
}Poll the job
curl -H "Authorization: Bearer bmi_YOUR_KEY" "https://bmiapi.com/api/v1/jobs/job_example?claim=EXAMPLE"
Final poll
{
"jobId": "fixture-job-success",
"requestId": "fixture-request-success",
"createdAt": "2026-10-26T15:00:00.000Z",
"status": "completed",
"startedAt": "2026-10-26T15:00:03.000Z",
"completedAt": "2026-10-26T15:00:06.291Z",
"errorCode": null,
"queueDepth": null,
"response": {
"resultFamily": "works",
"data": {
"metadata": {
"resultFamily": "works",
"searchType": "Title",
"primaryFilter": "Title",
"primaryValue": "Stop",
"secondaryFilter": null,
"secondaryValue": null,
"searchDatabase": "Songview",
"pageNumber": 1,
"viewCount": 20,
"dedupeApplied": true,
"rawSearchContext": null,
"encodedSearchContext": null
},
"results": [
{
"workTitle": "STOP",
"bmiWorkId": "123",
"songViewStatus": "Reconciled",
"iswc": "T0701420714",
"ascapWorkId": "490322031",
"alternateTitles": [
"STOP AND SMELL THE ROSES"
],
"derived": {
"listedTotalPercent": 100,
"unlistedPercent": 0,
"societies": [],
"shareTotals": null
},
"awards": [],
"proShares": [
{
"organization": "BMI",
"percentControlled": "50%",
"workId": "123",
"note": null
},
{
"organization": "ASCAP",
"percentControlled": "50%",
"workId": "490322031",
"note": null
}
],
"writers": {
"percentBreakdown": [
{
"organization": "BMI",
"percent": "50%",
"note": null
}
],
"contributors": [
{
"name": "DAVIS MAC",
"affiliation": "BMI",
"ipiNumber": "782249809",
"ipiNameNumber": "00782249809",
"catalog": null,
"isAffiliatedWithBmi": true
}
]
},
"performers": {
"percentBreakdown": [],
"values": {
"raw": [],
"deduped": []
}
},
"publishers": {
"percentBreakdown": [],
"entries": [
{
"name": "SONG PUBLISHING",
"affiliation": "BMI",
"ipiNumber": "1",
"ipiNameNumber": "00000000001",
"isAffiliatedWithBmi": true,
"catalog": null,
"contactInfo": null,
"notes": []
}
],
"hasOtherNonAscapOrBmiPublishers": null,
"otherPublishersNotice": "Other Participating Publishers"
}
}
]
},
"pagination": {
"pageNumber": 1,
"viewCount": 20,
"totalPages": 1,
"totalResults": 1,
"totalResultsIsLowerBound": false,
"hasNextPage": false,
"hasPreviousPage": false,
"resultsOnPage": 0,
"summary": ""
},
"warnings": [
"value-unknown: publishers.hasOtherNonAscapOrBmiPublishers is null for 1 work(s) because BMI printed a newer other-publishers label (see publishers.otherPublishersNotice) instead of \"Other Non-ASCAP and Non-BMI Publishers\", and the newer label does not say whether those publishers belong to ASCAP or BMI. BMI Work IDs: 123"
],
"querySuggestions": [],
"meta": {
"apiVersion": "v1",
"requestId": "fixture-request-success",
"jobId": "fixture-job-success",
"cached": false,
"durationMs": 1240
}
}
}Rate limits, quota, and errors
Read Retry-After, X-Request-Id, and the quota headers X-Bmiapi-Quota-Used, X-Bmiapi-Quota-Limit, X-Bmiapi-Quota-Reset, and X-Bmiapi-Quota-Warning. Saved answers are free, up to 300 a minute per key. Saved answers always carry X-Bmiapi-Quota-Approximate: true and leave out X-Bmiapi-Quota-Used and X-Bmiapi-Quota-Warning; a live lookup carries the exact figure. Live lookups are 10/min on Free, 30/min on Builder, and 120/min on Label. Free has 10 live lookups per calendar month, resetting on the 1st (UTC); Builder has 50 a day and Label 1,000 a day, each resetting at 00:00 UTC. Every response carries X-Request-Id, a server id to quote to support; send your own tag in X-Client-Request-Id (letters, digits and ._:-, up to 64) and it comes back in the same header.
| HTTP | code | What to do |
|---|---|---|
| 400 | VALIDATION | Fix the field named in issues, then resend. |
| 401 | INVALID_ | Check the Bearer key or rotate it. |
| 403 | FORBIDDEN | This key cannot use the operation. |
| 404 | NOT_ | Check the path or job id. |
| 409 | IDEMPOTENCY_ | Reuse an idempotency key only with the same body. |
| 429 | QUOTA_ | Wait Retry-After; saved answers remain free. |
| 502 | SCRAPE_ | Retry with backoff; the live lookup did not complete. |
| 503 | UPSTREAM_ | BMI rejected the session; check /status. |
| 504 | TIMEOUT | Stop polling this job and start a new request later. |
Optional progress stream
Send Accept: text/event-stream to watch the same request. The stream is optional; without it, status codes and JSON bodies are unchanged. Events are saved, turn, asking, answered, then result. A saved hit sends saved and result immediately.
event: saved
data: {"hit":false,"at":40}
event: turn
data: {"granted":true,"at":60}
event: asking
data: {"at":90}
event: answered
data: {"at":3090,"ms":3000,"spans":{}}
event: result
data: {"status":200,"serverTiming":"…","body":{}}MCP endpoint
Connect by URL: give the client https://bmiapi.com/mcp, click Connect, sign in. Or send Authorization: Bearer bmi_… as a request header. It is stateless Streamable HTTP with JSON responses.
| Tool | What it answers | Inputs | Cost |
|---|---|---|---|
| search_songs | Works by title, with society shares and registered publisher contacts | title (required); secondaryFilter with secondaryValue (Performer, Writer/Composer or Publisher); pageNumber; viewCount (20, 50 or 100) | free when saved, otherwise 1 live lookup |
| search_writers | Writers by name, with two preview titles; with catalog, every work in that writer's catalog | writerComposerName (required); catalog from a result's catalogQuery; pageNumber; viewCount (a catalog page uses 50) | free when saved, otherwise 1 live lookup per page |
| search_publishers | Publishers by name, with contacts and two preview titles; with catalog, every work in that publisher's catalog | publisherName (required); catalog; pageNumber; viewCount (a catalog page uses 50) | free when saved, otherwise 1 live lookup per page |
| search_performers | Performer credits and work previews by name | performerName (required); secondaryFilter with secondaryValue; pageNumber; viewCount | free when saved, otherwise 1 live lookup |
| find_song_by_iswc | One work by ISWC | iswc (required) | free when saved, otherwise 1 live lookup |
| find_song_by_bmi_work_id | One work by BMI Work ID | bmiWorkId (required) | free when saved, otherwise 1 live lookup |
| check_lookup | A queued lookup's place in line, or its answer | jobId (required) | free |
| list_my_workspaces | Your active memberships and workspace IDs; creates nothing | No arguments | No BMI lookup; key request caps apply |
| list_forensics_result_sets | Workspaces grouped with their result sets | Optional workspaceId | No BMI lookup; key request caps apply |
| create_forensics_result_set | A durable publishing question and plan | workspaceId, name, question; optional plan | No BMI lookup; key request caps apply |
| update_forensics_result_set | Edit name, question, recall or plan | setId, patch | No BMI lookup; key request caps apply |
| delete_forensics_result_set | Delete a set and its live evidence; blocked during active work | setId | No BMI lookup; key request caps apply |
| load_forensics_recordings | Load up to 100 songs and 300 recordings; single call at most 8 MiB with bounded free text | setId, load containing songs and recordings. Song and recording IDs use at most 200 Unicode code points. After trimming, titles, artists and ISWCs use at most 200 UTF-16 units with no interior control characters. Other free text uses 1,000 code points, and ISRCs and external IDs 256. A writer's normalized search surname also fits 200 UTF-16 units. Serialized song evidence is limited to 900,000 bytes. Each song accepts 50 ISWCs, 50 writers and 600 sources; each recording accepts 50 sources. Version-only titles remain loadable; if no identifier answer is available, a run finishes as search_refused without issuing an empty title query. | No BMI lookup; key request caps apply |
| rescope_forensics_recordings | Set or clear up to 300 recording exclusions, or change tiers with an auditable basis, then recompute affected songs and run totals | setId, recordings containing recordingId and exclusionReason, with optional tier plus basis; unique IDs; strict 64 KiB JSON cap | No BMI lookup; key request caps apply |
| get_forensics_result_set | Viewer role, counts, plan, map version and runs | setId | No BMI lookup; key request caps apply |
| get_forensics_rows | A bounded page of compact current recording rows | setId; optional limit (1–2,000, default 1,000), opaque cursor and since ISO timestamp; use returned asOf for the next since poll (rows may repeat) | No BMI lookup; key request caps apply |
| get_forensics_evidence | Retained registrations, proof and matched map lines. Evidence uses a 5 MiB budget. The current decision's song, registrations and map lines are always retained together, even if that basis alone exceeds the budget. Required decision evidence is included first, then the song's recordings, then optional history selected newest-run-first within the remaining budget. Returned registrations and candidates keep their created-at/ID order. MCP includes at most 201 recordings; HTTP has no recording-count cap. recordingsOmitted, registrationsOmitted and candidatesOmitted count evidence left out of the reply. | setId, songId | No BMI lookup; key request caps apply |
| export_forensics_result_set | Small individual exports inline; large exports and batched exports return signed links. These links expire in 15 minutes. Open one in any browser or fetch it with plain curl; no key or sign-in is needed. After that, call export_forensics_result_set again for fresh links. | setId, format (csv/json/md); optional view facets | No BMI lookup; key request caps apply |
| start_forensics_run | Start sample, rest, recheck, settle or fixup | setId, run containing kind; optional maxLiveLookups and selected songIds | Sample/rest/fixup use saved answers first; recheck/settle spend live lookups; run cap and the plan's allowance apply |
| recheck_forensics_song | Start a reread of one retained song | setId, songId; optional maxLiveLookups | Sample/rest/fixup use saved answers first; recheck/settle spend live lookups; run cap and the plan's allowance apply |
| settle_forensics_checks | Start a bulk reread of queued open checks | setId; optional maxLiveLookups | Sample/rest/fixup use saved answers first; recheck/settle spend live lookups; run cap and the plan's allowance apply |
| pause_forensics_run | Pause dispatch and drain accepted jobs | setId, runId, expectedStatus | No BMI lookup; key request caps apply |
| resume_forensics_run | Resume with current actor billing; checkpoint starts a separate rest run | setId, runId, expectedStatus | Sample/rest/fixup use saved answers first; recheck/settle spend live lookups; run cap and the plan's allowance apply |
| stop_forensics_run | Stop dispatch and drain accepted jobs | setId, runId, expectedStatus | No BMI lookup; key request caps apply |
| raise_forensics_limit | Audited cap increase, at most 2250; does not resume | setId, runId, expectedStatus, maxLiveLookups | No BMI lookup; key request caps apply |
| override_forensics_song | Manual decision with reason/source; rule evidence survives. Evidence uses a 5 MiB budget. The current decision's song, registrations and map lines are always retained together, even if that basis alone exceeds the budget. Required decision evidence is included first, then the song's recordings, then optional history selected newest-run-first within the remaining budget. Returned registrations and candidates keep their created-at/ID order. MCP includes at most 201 recordings; HTTP has no recording-count cap. recordingsOmitted, registrationsOmitted and candidatesOmitted count evidence left out of the reply. Evidence-returning writes refuse with TOOBIG before committing when their required core exceeds the reply budget. The reply applies this write's song changes to an evidence snapshot read before the write; updatedAt is the committed song timestamp. GET the song again for the latest evidence after concurrent changes. | setId, songId, override containing decision, reason, source; bounded text | No BMI lookup; key request caps apply |
| clear_forensics_override | Reveal the latest retained rule verdict. Evidence uses a 5 MiB budget. The current decision's song, registrations and map lines are always retained together, even if that basis alone exceeds the budget. Required decision evidence is included first, then the song's recordings, then optional history selected newest-run-first within the remaining budget. Returned registrations and candidates keep their created-at/ID order. MCP includes at most 201 recordings; HTTP has no recording-count cap. recordingsOmitted, registrationsOmitted and candidatesOmitted count evidence left out of the reply. Evidence-returning writes refuse with TOOBIG before committing when their required core exceeds the reply budget. The reply applies this write's song changes to an evidence snapshot read before the write; updatedAt is the committed song timestamp. GET the song again for the latest evidence after concurrent changes. | setId, songId | No BMI lookup; key request caps apply |
| update_forensics_song_writers | Attach outside writers with a free-source URL and read time. Evidence uses a 5 MiB budget. The current decision's song, registrations and map lines are always retained together, even if that basis alone exceeds the budget. Required decision evidence is included first, then the song's recordings, then optional history selected newest-run-first within the remaining budget. Returned registrations and candidates keep their created-at/ID order. MCP includes at most 201 recordings; HTTP has no recording-count cap. recordingsOmitted, registrationsOmitted and candidatesOmitted count evidence left out of the reply. Evidence-returning writes refuse with TOOBIG before committing when their required core exceeds the reply budget. The reply applies this write's song changes to an evidence snapshot read before the write; updatedAt is the committed song timestamp. GET the song again for the latest evidence after concurrent changes. | setId, songId, update containing writers and source; 600-source cap returns SOURCES_CAP and asks support to review retained provenance | No BMI lookup; key request caps apply |
| redecide_forensics_result_set | Re-run the current rule over stored evidence | setId | No BMI lookup; key request caps apply |
Sign-in with OAuth is open to Claude, Grok and apps on your own computer such as Claude Code. A hosted agent or a web app sends an API key as the Authorization header instead.
Forensics reads require active workspace membership; every write requires the owner or staff who is also a member. Discover IDs with list_my_workspaces. Tool schemas and structured outputs come from tools/list. These tools retain result sets and evidence until set/workspace deletion. get_forensics_rows uses pages of 1,000 rows by default (2,000 maximum), an opaque cursor, a 4 MiB row-JSON bound and an asOf watermark; use that watermark as the next since value, expect a poll to repeat rows, and continue until nextCursor is null. HTTP /rows remains a complete response. A batch pairing tools/list with a full rows page can approach the 8 MiB reply limit. Song and recording IDs use at most 200 Unicode code points. After trimming, titles, artists and ISWCs use at most 200 UTF-16 units with no interior control characters. Other free text uses 1,000 code points, and ISRCs and external IDs 256. A writer's normalized search surname also fits 200 UTF-16 units. Serialized song evidence is limited to 900,000 bytes. Each song accepts 50 ISWCs, 50 writers and 600 sources; each recording accepts 50 sources. Version-only titles remain loadable; if no identifier answer is available, a run finishes as search_refused without issuing an empty title query. Evidence uses a 5 MiB budget. The current decision's song, registrations and map lines are always retained together, even if that basis alone exceeds the budget. Required decision evidence is included first, then the song's recordings, then optional history selected newest-run-first within the remaining budget. Returned registrations and candidates keep their created-at/ID order. MCP includes at most 201 recordings; HTTP has no recording-count cap. recordingsOmitted, registrationsOmitted and candidatesOmitted count evidence left out of the reply. A writer update at the 600-source cap returns SOURCES_CAP and asks support to review retained provenance. Each MCP tools/call reply is capped at 8 MiB; oversized replies return MCP_REPLY_TOO_LARGE.
A JSON-RPC batch runs only its first tools/call. Later calls keep their IDs and receive -32000 with data.code: MCP_BATCH_ONE_CALL; send each call in its own request. Initialize, ping, tools/list, notifications and other entries keep their normal behavior.
Sample, rest and fixup runs check saved answers first. Recheck and settle runs read BMI live. Runs may spend live lookups: at most 4 submissions per rolling minute, 20 waiting (also limited by plan), and 2250 per run. Owners use their plan allowance; staff use 20,000 per UTC day. Saved answers cost zero BMI but respect key caps. A sample pauses at a checkpoint; resume starts a separate rest run. Pause and stop drain accepted jobs. Explicit resume uses the current actor’s allowance.
HTTP uses /api/v1/forensics/result-sets with a BMI key or session; session writes require the same origin. The OpenAPI contract includes load, rows, evidence, exports, scope edits and run controls. Stale controls return 409 run_changed; another active run returns 409 another_run_active. Exports apply current server facets (OR within each facet, AND across facets), include row-count headers, and name unfinished sets partial. Recording scope accepts a nullable exclusion reason; a row may also supply a new tier and required basis, and the previous tier, actor and time remain auditable. Excluded rows retain their tier and all evidence, while a song remains in scope if another recording is eligible. The scope edit is owner/staff-only, bounded to 300 unique rows and a 64 KiB body, idempotent, and is refused with 409 run_changed while a run has active work or a lease. Registry shares are by society, never by publisher; decision proof and its dated map explain the basis.
Claude Code
claude mcp add --transport http bmiapi https://bmiapi.com/mcp
Then run claude, type /mcp, and sign in to bmiapi. With a key instead of signing in, add --header "Authorization: Bearer bmi_…".
Claude.ai and Claude Desktop
- In Claude, open Customize, then Connectors. Click + Add, then Add custom connector.
- Name it bmiapi and paste the address. If Claude asks how to register, pick Register automatically. Click Connect.
- Sign in to bmiapi (a free account works). Ask Claude who wrote a song.
Grok
- On grok.com, open Plugins, then the Connectors tab, then New Connector, then Custom.
- Name it bmiapi, paste the address, and add the connector.
- Sign in to bmiapi when Grok asks. Ask Grok who controls a song.
Run a list
Set BMIAPI_KEY in your environment. Save and run the Python example with python3 (songs.csv needs a title column), or install zod and run the TypeScript example with Node 22.21.0. Both handle 202 and 429, honor Retry-After, back off, and resume the same request or running job. They neutralize spreadsheet formulas and preserve quotes and newlines in CSV.
export BMIAPI_KEY="bmi_YOUR_KEY"
Python
import csv
import os
import time
import urllib.request
import urllib.error
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
import json
def safe_cell(value):
text = "" if value is None else str(value)
# Tab and CR are dangerous even when followed by ordinary text.
index = 0
while index < len(text) and text[index].isspace() and text[index] not in "\t\r":
index += 1
if index < len(text) and text[index] in "=+-@\t\r":
return "'" + text
return text
def request(url, key, body=None):
headers = {"Authorization": f"Bearer {key}"}
data = None
if body is not None:
headers["Content-Type"] = "application/json"
data = json.dumps(body).encode()
try:
response = urllib.request.urlopen(urllib.request.Request(url, data=data, headers=headers))
except urllib.error.HTTPError as error:
if error.code != 429:
raise
response = error
with response:
return response.status, response.headers, json.load(response)
def retry_delay(headers, fallback):
value = headers.get("Retry-After", "")
try:
advice = float(value)
except ValueError:
try:
advice = (parsedate_to_datetime(value) - datetime.now(timezone.utc)).total_seconds()
except (ValueError, TypeError, OverflowError):
advice = 0
return max(advice, fallback)
def request_with_backoff(url, key, body=None):
backoff = 1
while True:
status, headers, answer = request(url, key, body)
if status != 429:
return status, headers, answer
time.sleep(retry_delay(headers, backoff))
backoff = min(backoff * 2, 60)
def lookup(title, key):
status, headers, answer = request_with_backoff("https://bmiapi.com/api/v1/title-search", key, {"title": title})
if status != 202:
return answer
poll_url = answer["pollUrl"]
while True:
time.sleep(retry_delay(headers, answer.get("retryAfterSeconds", 3)))
_, headers, answer = request_with_backoff(poll_url, key)
if answer["status"] == "completed":
return answer["response"]
if answer["status"] == "failed":
raise RuntimeError(answer["errorCode"])
def main():
key = os.environ["BMIAPI_KEY"]
with open("songs.csv", newline="", encoding="utf-8") as src, open("bmiapi-results.csv", "w", newline="", encoding="utf-8") as out:
writer = csv.writer(out)
writer.writerow(["Input", "Work title", "BMI Work ID", "ISWC", "Warning"])
for row in csv.DictReader(src):
envelope = lookup(row["title"], key)
for work in envelope["data"]["results"]:
writer.writerow([safe_cell(value) for value in [row["title"], work.get("workTitle"), work.get("bmiWorkId"), work.get("iswc"), " | ".join(envelope["warnings"])]])
if __name__ == "__main__":
main()
TypeScript
import { writeFile } from "node:fs/promises";
import { pathToFileURL } from "node:url";
import { z } from "zod";
// Validate the fields this recipe reads; the complete schema is in /api/openapi.
const answerSchema = z.object({
data: z.object({
results: z.array(
z.object({
workTitle: z.string(),
bmiWorkId: z.string().nullable(),
iswc: z.string().nullable(),
}),
),
}),
warnings: z.array(z.string()),
});
const acceptedSchema = z.object({
pollUrl: z.string().url(),
retryAfterSeconds: z.number().positive(),
});
const jobSchema = z.object({
status: z.enum(["queued", "scraping", "completed", "failed"]),
response: z.unknown(),
errorCode: z.string().nullish(),
retryAfterSeconds: z.number().nonnegative().optional(),
});
// Numbers calculated by this script stay numeric. Registry/input text is untrusted.
export function csvCell(value: string | number | null | undefined): string {
let text = String(value ?? "");
if (typeof value !== "number" && /^\s*[=+\-@\t\r]/u.test(text))
text = "'" + text;
return /[",\r\n]/u.test(text) ? '"' + text.replace(/"/gu, '""') + '"' : text;
}
function retryDelay(headers: Headers, fallback: number): number {
const value = headers.get("Retry-After");
if (!value) return fallback;
const seconds = Number(value);
const advice = Number.isFinite(seconds) ? seconds : (Date.parse(value) - Date.now()) / 1000;
return Number.isFinite(advice) ? Math.max(advice, fallback) : fallback;
}
const wait = (seconds: number) => new Promise<void>((resolve) => setTimeout(resolve, seconds * 1000));
async function requestWithBackoff(url: string, init: RequestInit) {
let backoff = 1;
while (true) {
const response = await fetch(url, init);
if (response.status !== 429) return response;
await response.body?.cancel();
await wait(retryDelay(response.headers, backoff));
backoff = Math.min(backoff * 2, 60);
}
}
export async function lookup(title: string, key: string) {
let response = await requestWithBackoff("https://bmiapi.com/api/v1/title-search", {
method: "POST",
headers: {
Authorization: `Bearer ${key}`,
"content-type": "application/json",
},
body: JSON.stringify({ title }),
});
if (response.status === 202) {
const accepted = acceptedSchema.parse(await response.json());
let delay = accepted.retryAfterSeconds;
while (true) {
await wait(retryDelay(response.headers, delay));
response = await requestWithBackoff(accepted.pollUrl, {
headers: { Authorization: `Bearer ${key}` },
});
if (!response.ok) throw new Error(await response.text());
const job = jobSchema.parse(await response.json());
if (job.status === "completed") return answerSchema.parse(job.response);
if (job.status === "failed")
throw new Error(job.errorCode ?? "Lookup failed");
delay = job.retryAfterSeconds ?? 3;
}
}
if (!response.ok) throw new Error(await response.text());
return answerSchema.parse(await response.json());
}
async function main() {
const key = process.env.BMIAPI_KEY;
if (!key) throw new Error("Set BMIAPI_KEY to your API key.");
const titles = ["Stand by Me", "What's Going On"];
const rows: (string | number | null | undefined)[][] = [
["Input", "Work title", "BMI Work ID", "ISWC", "Warning"],
];
for (const title of titles) {
const envelope = await lookup(title, key);
for (const work of envelope.data.results) {
rows.push([
title,
work.workTitle,
work.bmiWorkId,
work.iswc,
envelope.warnings.join(" | "),
]);
}
}
await writeFile(
"bmiapi-results.csv",
rows.map((row) => row.map(csvCell).join(",")).join("\r\n") + "\r\n",
);
}
if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url)
await main();
Vocabulary
| Saved answer | A stored response, free, with its age. |
| Live lookup | A request sent to BMI now. Uses one live lookup from the available balance. |
| Work / song | The composition registration, not a recording or master. |
| Share / % controlled | A society-level percentage. bmiapi never infers a per-person split. |
| Not listed in Songview | The remainder the registry does not list on that page. |
| Reconciled | BMI's word for a work whose writers, publishers and shares the Songview societies (BMI, ASCAP, SESAC and GMR) agree on. Societies outside Songview have not confirmed it. |
| Rounding | BMI rounds each writer's and publisher's share to the hundredth, so a work's listed shares can add up to a little more or less than 100%, such as 100.03% or 99.99%. bmiapi calls that rounding and shows BMI's numbers as listed, never adjusted. |
| NS | No society. BMI lists no performing rights society for this writer or publisher. A share can still name BMI or ASCAP: the share says which society licenses it, which is a separate fact from the person's own membership. |
| AMRA | The American Mechanical Rights Agency, a US royalty collection agency owned by Kobalt. It shows up as the affiliation for some writers and publishers whose royalties it collects. |
| Other society names | BMI prints each writer's and publisher's society by its short name: ASCAP, SESAC and GMR in the US, PRS in the UK, SOCAN in Canada, APRA in Australia and New Zealand, GEMA in Germany, SACEM in France, STIM in Sweden, BUMA in the Netherlands, JASRAC in Japan, and others. “Other” in the shares is a share BMI lists without naming the society. |
| IPI name # | An 11-digit number for one registered name, not for one person. A songwriter can have several: one for a legal name and one for each professional name. Songview shows only these name numbers, not the IPI base number that ties one person's names together, so the same songwriter can appear on different works under different names and numbers. |
| Catalog | Every work BMI lists for one writer or publisher, a page at a time. A writer search finds the person; their catalog lists the works, each with its BMI Work ID. |