CoolFace
Apppublic

marconolimits/NMT

sourceHugging Faceupdated 4mo agoView on Hugging Face
1likes
HF_API_INTEGRATION.md178 linesDownload Raw Back to root
1# Integrating external software with the Hugging Face NMT API2 3Use this when you connect **another app** (game, mobile app, desktop tool, backend service) to the **hosted** translator on Hugging Face—not your local machine.4 5## Production endpoint6 7| Item | Value |8|------|--------|9| **Base URL** | `https://marconolimits-nmt.hf.space` |10| **Protocol** | HTTPS only |11| **Space (dashboard)** | [huggingface.co/spaces/marconolimits/NMT](https://huggingface.co/spaces/marconolimits/NMT) |12 13All paths below are relative to the base URL (e.g. full health URL: `https://marconolimits-nmt.hf.space/healthz`).14 15---16 17## Authentication18 19If the Space has **`REQUIRE_API_KEY=1`** and secret **`NMT_API_KEY`** set in [Space settings](https://huggingface.co/spaces/marconolimits/NMT/settings), every **translation** request must include:20 21```http22X-API-Key: <your NMT_API_KEY value>23```24 25- **`GET /healthz`** does **not** require a key (use for monitoring).26- **`GET /`** (HTML help) does **not** require a key.27- **`POST /translate`** and **`GET /translate`** require the key when enforcement is on.28 29Store the key in **environment variables** or a **secure secret store** in your app—never commit it to Git or embed it in public client binaries if you can avoid it.30 31---32 33## Endpoints34 35### 1) Health check36 37```http38GET /healthz39```40 41**Response 200:** `{"status":"ok"}`42 43Use this before showing “translator online” or in uptime checks.44 45---46 47### 2) Translate (recommended: POST + JSON)48 49```http50POST /translate51Content-Type: application/json52X-API-Key: <optional if enforcement off>53 54{"text":"Your English sentence here."}55```56 57**Response 200:**58 59```json60{61  "translation": "Italian text here.",62  "latency_ms": 123.4,63  "request_id": "..."64}65```66 67**Typical errors**68 69| Code | Meaning |70|------|--------|71| 401 | Missing/wrong `X-API-Key` |72| 400 | Bad body (e.g. missing `text`, invalid JSON)—body may include `hint` |73| 413 | Text longer than `MAX_INPUT_CHARS` |74| 504 | Translation timed out |75| 415 | Unsupported `Content-Type` for POST |76 77---78 79### 3) Translate (GET, short text only)80 81```http82GET /translate?text=Hello83X-API-Key: <optional if enforcement off>84```85 86URL-encode `text` if it contains spaces or special characters. Prefer **POST** for long sentences (URL length limits).87 88---89 90## Minimal examples (copy and adapt)91 92### cURL93 94```bash95curl -sS "https://marconolimits-nmt.hf.space/healthz"96 97curl -sS -X POST "https://marconolimits-nmt.hf.space/translate" \98  -H "Content-Type: application/json" \99  -H "X-API-Key: YOUR_KEY_HERE" \100  -d "{\"text\":\"Hello, how are you?\"}"101```102 103### Python (this repo)104 105Use the bundled client so JSON and headers stay correct:106 107```python108from scripts.nmt_client import translate109 110r = translate(111    "https://marconolimits-nmt.hf.space",112    "Hello, how are you?",113    api_key="YOUR_KEY_HERE",  # omit if API key is disabled on the Space114)115print(r.translation)116```117 118### C# / .NET (`HttpClient`)119 120```csharp121using var client = new HttpClient { BaseAddress = new Uri("https://marconolimits-nmt.hf.space/") };122client.DefaultRequestHeaders.Add("X-API-Key", "YOUR_KEY_HERE"); // if required123 124var json = """{"text":"Hello, how are you?"}""";125using var content = new StringContent(json, Encoding.UTF8, "application/json");126var resp = await client.PostAsync("translate", content);127resp.EnsureSuccessStatusCode();128var body = await resp.Content.ReadAsStringAsync();129// Parse JSON: translation, latency_ms, request_id130```131 132### JavaScript / TypeScript (Node or server)133 134```javascript135const res = await fetch("https://marconolimits-nmt.hf.space/translate", {136  method: "POST",137  headers: {138    "Content-Type": "application/json",139    "X-API-Key": process.env.NMT_API_KEY, // if required140  },141  body: JSON.stringify({ text: "Hello, how are you?" }),142});143const data = await res.json();144// data.translation145```146 147---148 149## Calling from a **browser** (web app)150 151Browsers enforce **CORS**. This API does not add permissive CORS headers by default, so **direct `fetch()` from a random website to `marconolimits-nmt.hf.space` may be blocked**.152 153**Recommended:** call the API from **your backend** (same origin as your web app), and have the frontend talk to your backend. Your backend adds `X-API-Key` and never exposes the key to the browser.154 155If you must call from the browser only, you may need a **proxy** or **CORS configuration** on a server you control—not covered here.156 157---158 159## Operational notes160 161- **Cold start:** Free Spaces can **sleep**. The first request after idle may take **tens of seconds**; retries with backoff help.162- **HTTPS:** Always use `https://` (certificate is managed by Hugging Face).163- **Limits:** Respect `MAX_INPUT_CHARS` (default 2000 unless changed in Space env).164- **Same key everywhere:** Use the **same** `NMT_API_KEY` value you configured in the Space **Variables and secrets** panel.165 166---167 168## Checklist for a new integration169 1701. Confirm the Space is **Running** on the [Space page](https://huggingface.co/spaces/marconolimits/NMT).1712. Confirm **`NMT_API_KEY`** / **`REQUIRE_API_KEY`** in Space settings match what your app sends.1723. Implement **POST `/translate`** with **`Content-Type: application/json`** and body **`{"text":"..."}`**.1734. Send **`X-API-Key`** when enforcement is on.1745. Parse JSON response fields **`translation`**, **`latency_ms`**, **`request_id`**.1756. For production web UIs, prefer **backend-to-Hugging Face**, not **browser-to-Hugging Face**, unless you have solved CORS and key secrecy.176 177For Space-specific Git push and env setup, see [HUGGINGFACE_SPACES.md](HUGGINGFACE_SPACES.md).178