China Company Verification API in Python
Build a Python lookup client that searches for Chinese companies, displays candidates, and verifies a selected company by name or credit code.
Retrieve a company’s registered identity, business status, address, capital and business scope.

This Python example uses ChinaValidate to search for a Mainland Chinese company and retrieve its registry profile. It uses only the standard library. Start with a phrase to inspect candidates or pass a Chinese legal name or Unified Social Credit Code directly to the profile operation. The program has separate arguments for the two calls, so showing the first candidate never triggers an additional paid lookup.
The API has two layers of response handling. The HTTP client must receive a valid response, and the JSON envelope must report a successful application code. A successful search can contain zero rows. The example lets the caller distinguish those conditions before deciding how to proceed.
Prepare the input and run the program
Use a current Python 3 installation and a ChinaValidate API key with API credits. Place the key in CHINAVALIDATE_API_KEY in the environment that runs the program. Save the source below as company_lookup.py. Run the search mode with a Chinese keyword from an authorized source document. The working directory need not contain a configuration file. Use a secret manager or the deployment environment to provide the key in a service. Python urllib.request documentation · ChinaValidate quick start
python3 company_lookup.py search "$COMPANY_KEYWORD"
python3 company_lookup.py profile "$COMPANY_IDENTITY"
COMPANY_KEYWORD is a search phrase. COMPANY_IDENTITY is a verified 18-character credit code or the complete Chinese registered name. Set them to values you are authorized to query. The commands are independent. You can run profile directly with a known identifier or inspect the printed candidate list before making the second call. The program uses the default Chinese response language explicitly so its behavior is visible in the request.
The standard library percent-encodes the search query and serializes the profile payload as UTF-8 JSON. Keep identifiers as strings throughout. A supplier's English display name can help a human locate the correct row. The field sent to the profile operation is the original Chinese name or credit code verified for the same legal entity. Company Search API input · Company Profile API input
The Python client
The client shares the transport and envelope check between both calls. It does not repeat a request automatically. The example reports the request identifier to standard error when available and prints only the selected fields from the original data. These choices make the command usable either by a person or as a starting point for an application that saves its own structured result.
import argparse
import json
import os
import sys
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
BASE = "https://api.chinavalidate.com"
def lookup(path, key, *, query=None, payload=None):
target = BASE + path
if query:
target += "?" + urlencode(query)
headers = {"Authorization": "Bearer " + key, "Accept": "application/json"}
body = None
if payload is not None:
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
headers["Content-Type"] = "application/json"
request = Request(target, data=body, headers=headers)
try:
with urlopen(request, timeout=30) as response:
reference = response.headers.get("X-CV-Request-Id")
if reference:
print(f"Request ID: {reference}", file=sys.stderr)
envelope = json.load(response)
except HTTPError as exc:
raise ValueError(f"HTTP status {exc.code}") from exc
except (URLError, TimeoutError) as exc:
raise ValueError("No complete response received") from exc
if not isinstance(envelope, dict):
raise ValueError("Expected a JSON object")
if envelope.get("code") != 200:
raise ValueError(f"API code: {envelope.get('code')}")
data = envelope.get("data")
if not isinstance(data, dict) or not isinstance(data.get("items"), list):
raise ValueError("Expected a data.items array")
return data
def main():
parser = argparse.ArgumentParser()
parser.add_argument("operation", choices=["search", "profile"])
parser.add_argument("value")
args = parser.parse_args()
key = os.environ.get("CHINAVALIDATE_API_KEY")
if not key:
parser.error("Set CHINAVALIDATE_API_KEY")
if args.operation == "search":
data = lookup(
"/v1/companies/search",
key,
query={"keyword": args.value, "page": 1, "language": "zh-CN"},
)
else:
data = lookup(
"/v1/companies/profile",
key,
payload={"company_name_or_credit_code": args.value, "language": "zh-CN"},
)
fields = ("company_name", "unified_social_credit_code", "business_status")
rows = [{field: row.get(field) for field in fields} for row in data["items"]]
print(json.dumps({"total_count": data.get("total_count"), "items": rows},
ensure_ascii=False, indent=2))
if __name__ == "__main__":
try:
main()
except (ValueError, TypeError, AttributeError) as error:
print(error, file=sys.stderr)
sys.exit(1)
The variable BASE is fixed to the documented host. The request does not come from a URL supplied by the person entering a company keyword. If you build a web form from the example, accept only the company input that the form needs. The server is responsible for choosing which documented path to call and for attaching its own credential. Keep raw response access within the part of the application that needs it.
The search command reads the first page and prints its total count. It does not retrieve subsequent pages automatically. If more entries exist, a web interface can offer another explicit request when the reviewer needs it. Retain the original keyword and page number with the response. Pagination is an additional call, and the response count is distinct from the number of rows received in the current result.
Match a candidate before opening a profile
Imagine a search displays companies with similar Chinese names. Check the source document for a complete name, credit code, locality or other identity information. The most useful input for a second call is the verified credit code or the full Chinese name for the company actually involved. If a candidate is still ambiguous, keep it on the selection list and ask for a more specific company record. Turning the first row into a profile automatically adds cost and can attach evidence to the wrong entity.
A full profile can supply fields that the compact output above leaves out. In a registry review, the available address, legal representative, registered capital and business scope may each answer different questions. Decide which ones your application supports before widening the printed output. If a source field is absent, display that fact or leave it unknown according to your application’s terminology. Avoid replacing unavailable values with a zero, an empty code or a default business status.
If you later add the requested language to the user interface, set it on the appropriate query string or request body. The API describes the translated view alongside the original data for non-Chinese requests with a result. Keep the identity selected from the original data. When rendering a translated display, hold on to the original Chinese registered name for any subsequent endpoint that expects it. OpenAPI schema and language contract
Inspect outcomes without paid calls
The most useful tests exercise the response shape and the review decisions independently. Feed saved response examples through your application’s parser before using a production account. The empty example below represents a successful request with no records. The top-level code and the empty array both matter. Your caller can print an empty list, prompt a user for a better input or leave the verification record open without raising a transport error.
{
"code": 200,
"msg": "ok",
"data": {
"total_count": 0,
"items": []
}
}
Run tests for one match, two similar candidates, no matches, an omitted field and an application error. Then simulate a non-JSON response or timeout separately. Keep diagnostic output on standard error so a program that consumes the JSON on standard output is not forced to parse logging messages. The example exits with a nonzero code for a failed request and with zero for a valid empty result. Use the program’s output rather than just its exit code to decide whether it found a company.
When you are ready to test the actual network connection, use one known identifier and a bounded number of API calls. The pricing rules explain how completed results, including ordinary no-result lookups, use credits. If a call times out, completion may be uncertain from the client’s side. Record the operation, local timestamp and any request identifier before you repeat an attempt. This information also helps distinguish a bad input from an authentication or balance problem.
Move from the command line to an application
Reuse the transport and response parsing before adding workflow rules. An internal portal can first show candidate names and let an operator make a selection. A scheduled application can start with a verified identity already saved in its system. In both designs, persist the input, the selected legal identity and the outcome as separate facts. Store receipt time alongside a reusable result so the next user can tell when it was obtained.
Keep the first version small enough to inspect. Run the example with a single permitted search and a profile lookup only after confirming the selected company. Once the response behavior is clear, add the fields and display rules the application actually needs. The same request functions can support a command-line tool, a private service or a server-backed form without changing the identity rules that make the underlying lookup interpretable.
If an existing service needs to consume the command's output, agree on a small handoff first. Test a profile with a Chinese name that contains punctuation and a response with an omitted business status. Pass those values through the same storage path as a typical result. The source text and missing-value state should still be recognizable when the record is later read.