From 4441e61deaaa16f1a1a6929a6f0ec229758bb2ba Mon Sep 17 00:00:00 2001 From: mdevolde Date: Thu, 11 Jun 2026 18:20:58 +0200 Subject: [PATCH] feat(server): add the possibility to attach an api key --- README.md | 17 +++++++++++++++++ language_tool_python/server.py | 24 ++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/README.md b/README.md index aa51afa..37c6211 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,23 @@ with language_tool_python.LanguageToolPublicAPI("es") as tool: print(matches) ``` +#### Public LanguageTool API with an API key + +If you have a LanguageTool API key, set `premium_key` before calling `check()`: + +```python +import os + +import language_tool_python + +with language_tool_python.LanguageToolPublicAPI("en-US") as tool: + tool.premium_key = os.environ["LANGUAGETOOL_API_KEY"] + matches = tool.check("This are bad.") + print(matches) +``` + +The key is sent to the public API as `apiKey` for each request. + ### Your own remote LanguageTool server ```python diff --git a/language_tool_python/server.py b/language_tool_python/server.py index 84da34a..2fb094c 100644 --- a/language_tool_python/server.py +++ b/language_tool_python/server.py @@ -207,6 +207,9 @@ class LanguageTool: _proxies: dict[str, str] | None """A dictionary of proxies for network requests (used in requests to the server).""" + _premium_key: str | None + """The premium API key for the LanguageTool API.""" + def __init__( # noqa: PLR0913 # Too many arguments, but they are all necessary for configuring the server. Maybe refactor in a future breaking release to use a configuration object instead of individual parameters. self, language: str | None = None, @@ -285,6 +288,7 @@ def __init__( # noqa: PLR0913 # Too many arguments, but they are all necessary self._enabled_rules_only = False self._preferred_variants = set() self._picky = False + self._premium_key = None def __enter__(self) -> LanguageTool: """Enter the runtime context related to this object. @@ -577,6 +581,24 @@ def picky(self, value: bool) -> None: """ self._picky = value + @property + def premium_key(self) -> str | None: + """Get the premium API key. + + :return: The premium API key if set, otherwise None. + :rtype: str | None + """ + return self._premium_key + + @premium_key.setter + def premium_key(self, value: str | None) -> None: + """Set the premium API key. + + :param value: The premium API key. + :type value: str | None + """ + self._premium_key = value + @property def config(self) -> LanguageToolConfig | None: """Get the server configuration. @@ -756,6 +778,8 @@ def _create_params(self, text: str) -> dict[str, str]: params["preferredVariants"] = ",".join(self._preferred_variants) if self._picky: params["level"] = "picky" + if self._premium_key: + params["apiKey"] = self._premium_key return params def correct(self, text: str) -> str: