China Company Profile API in Rust
Use Rust, reqwest and Serde to request a Chinese company profile, handle the JSON response, and preserve original registry fields.
Retrieve a company’s registered identity, business status, address, capital and business scope.

Send the complete Chinese legal name or Unified Social Credit Code to the ChinaValidate company profile endpoint with a Rust client. This article builds a small command-line program using reqwest and Serde. It models the documented response, retains any unmodeled registry fields, and reports a valid empty result separately from an application error. You can reuse the same types in a server-side service.
The most useful place to start is a single identity you already know. The profile request takes a JSON object, so the example creates one using a serializable Rust value. It keeps the response language Chinese and prints the original result. If people later need readable translations, add a separate view for the returned translation rather than changing the key your system uses to identify a company.
Install the client dependencies
Start a Cargo binary project with the commands below and save the program in src/main.rs. The example uses a blocking client for a simple command. An async service can implement the same envelope and data types with a reusable asynchronous client. The blocking feature enables the example's request methods, while the JSON feature provides serialization and deserialization support. reqwest client documentation · Serde struct attributes
cargo new company-profile
cd company-profile
cargo add reqwest --features blocking,json
cargo add serde --features derive
cargo add serde_json
Put your API key in CHINAVALIDATE_API_KEY in the environment that runs Cargo. Supply the known legal name or credit code as one argument. The caller should not pass a secret in the command-line argument, since command arguments and shell commands may be recorded in several places. If you adapt the sample to a server, keep the key in server-side configuration and reuse a client rather than creating one for each operation. ChinaValidate API authentication
Model the reply without losing optional data
The documented success shape has a data object with a count and items. Registry properties depend on the source record. The sample models the company name, code and status as optional strings and keeps the remaining fields in a map. That avoids implementing all the registry fields just to see a useful result. Its output is intentionally short, so you can choose which other recorded fields to display when the application has a clear use for them. See the Company Profile API for the request and full examples.
use reqwest::blocking::Client;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::{env, error::Error, io, time::Duration};
const URL: &str = "https://api.chinavalidate.com/v1/companies/profile";
#[derive(Serialize)]
struct Query<'a> {
company_name_or_credit_code: &'a str,
language: &'a str,
}
#[derive(Deserialize)]
struct Envelope {
code: u16,
data: Value,
}
#[derive(Deserialize)]
struct ProfileData {
total_count: usize,
items: Vec<Company>,
}
#[derive(Deserialize)]
struct Company {
company_name: Option<String>,
unified_social_credit_code: Option<String>,
business_status: Option<String>,
#[serde(flatten)]
other_fields: Map<String, Value>,
}
fn error(message: impl Into<String>) -> io::Error {
io::Error::other(message.into())
}
fn retrieve(client: &Client, api_key: &str, identity: &str) -> Result<ProfileData, Box<dyn Error>> {
let response = client
.post(URL)
.bearer_auth(api_key)
.json(&Query { company_name_or_credit_code: identity, language: "zh-CN" })
.send()?;
let request_id = response.headers().get("X-CV-Request-Id")
.and_then(|value| value.to_str().ok()).unwrap_or("-").to_owned();
let response = response.error_for_status()?;
let envelope: Envelope = response.json()?;
if envelope.code != 200 {
return Err(error(format!("API code {}, request {}", envelope.code, request_id)).into());
}
Ok(serde_json::from_value(envelope.data)?)
}
fn main() -> Result<(), Box<dyn Error>> {
let api_key = env::var("CHINAVALIDATE_API_KEY")?;
let identity = env::args().nth(1).filter(|text| !text.trim().is_empty())
.ok_or_else(|| error("Supply a Chinese legal name or credit code"))?;
let client = Client::builder().timeout(Duration::from_secs(30)).build()?;
let profiles = retrieve(&client, &api_key, identity.trim())?;
println!("Profiles: {}", profiles.total_count);
for row in profiles.items {
println!("{} | {} | {} | {} additional fields",
row.company_name.as_deref().unwrap_or("[unavailable]"),
row.unified_social_credit_code.as_deref().unwrap_or("[unavailable]"),
row.business_status.as_deref().unwrap_or("[unavailable]"),
row.other_fields.len());
}
Ok(())
}
cargo run -- "$COMPANY_IDENTITY"
The program decodes the application envelope before parsing a successful data object. This is relevant because an error can have a different data shape. If a profile field represented by a string changes to another JSON type, the example returns a decoding error rather than coercing it into a company identity. Where the schema says a value can have multiple types, consider using a JSON value or a deliberately chosen untagged type backed by actual examples. Keep the selected identity strict enough to avoid merging records by an unverified value.
Identify which company the row represents
The example prints the original material, which may contain names, addresses or statuses in Chinese. Compare the original credit code with your input when it was supplied independently. If you used a legal name, compare the full value with the source from which you took it. If your system already has a company identifier, keep the confirmation step visible when the result comes back with limited data. A missing code deserves its own state, particularly if your system would otherwise store the returned name as a substitute key.
An Option field makes a compact view easy to render. It collapses missing and JSON null in this example. If the two have different meanings in your application, preserve the original record or inspect whether the key appears before deserialization into a more restricted type. An empty string can also be handled separately if your decision rules give it a specific meaning. Avoid assigning an active business status when no such value was returned.
When a non-Chinese response is useful, review the translation contract. The documentation describes a separate translated view for non-Chinese requests with a result, while the original data remains available. Carry the original legal name into calls that expect the company's Chinese name. Store translated values for reading and keep the original identifier for matching. The OpenAPI definition shows the envelopes for the supported operations.
Handle empty and unsuccessful requests
A valid empty profile response produces a count of zero and an empty items list. The program prints the count and no profile rows. Decide what should happen next at the application layer. A reviewer may need to obtain the exact Chinese name, check the original document, or record that the lookup returned nothing. Do not update a previously selected company's registration status because the current request returned no profile.
Keep transport failures separate from errors described by the API. In a service, use the application code and the request identifier when available. A connection timeout can occur before the client knows what the server completed. The sample does not automatically repeat a lookup. Before enabling retries in a billed workflow, decide how you will reconcile uncertain completion and prevent unnecessary requests. API pricing and charge rules
Profile lookups can be tested against three local fixtures: an available profile, a valid empty response, and an application error. Add a profile with an omitted field to check the display behavior. You can test these parser branches without making any paid requests. When the parser is ready, use one permitted call to check host, key and response against a company your team is authorized to query. Review the charged amount if it is returned.
Fit the client into a larger Rust application
Keep the API data model at the boundary and give the application a concise representation for decisions. A request function can return an exact profile or a result that needs further input. An application record can hold its company ID, the supplied lookup identifier, the time the response arrived and the verified identity from the data. The two structures serve different purposes. This separation makes it easier to add fields later without changing how previously saved decisions are interpreted.
If you switch to the asynchronous client, keep the shared transport and its timeout together and pass caller cancellation through your service. Avoid moving a blocking request into a high-concurrency async handler. Leave the lookup rules, response parsing and storage tests in place as you change the transport. Then check that original identifiers remain intact, optional values still show up accurately and a lookup returning nothing stays visibly distinct from a request that could not complete.
Keep decoding errors useful
Rust makes it practical to separate a failure to read the wire format from a decision about the company. For example, if the client receives a response with a valid envelope and an item whose code unexpectedly has a non-string type, the deserialization error should be observable. Preserve the operation, request identifier and time where available. That gives the integration owner enough information to inspect the contract or confirm whether the stored fixture needs correction.
For a service test, take one response that contains an optional registry detail outside the three named fields. Verify that it appears in the preserved map. Then test a result with a missing code and a translated name. Confirm that the application neither drops the additional field nor uses a display value in place of the original legal identifier. These checks are especially helpful when adding typed application fields after establishing the initial client.