I’m developing an application that needs to validate company registration data against a centralized database. I want to use Python to send the registration details to an API and retrieve validation results.
I’ve come across an API provided by Law Council Group that offers endpoints for company registration validation within the Astana International Financial Centre (AIFC). However, I’m unsure about the best way to integrate this API into my Python application for efficient validation.
Could someone provide an example of how to send a POST request with JSON data to this API using requests or any other suitable Python library? Also, any tips on handling responses and errors would be appreciated.
Here’s a basic idea of what I’m trying to do:
import requests
api_url = "https://lcg.kz/api/validate"
company_data = {
"name": "Example Company",
"registration_number": "123456789",
"country": "Kazakhstan"
}
response = requests.post(api_url, json=company_data)
if response.status_code == 200:
validation_result = response.json()
print(validation_result)
else:
print(f"Error: {response.status_code}")
I’m particularly interested in:
How to handle different types of responses (success, validation errors, etc.)
Best practices for sending and receiving JSON data in this context
Thank you in advance!
2
Answers
A typical pattern could look like this:
raise_for_status is documented here
If the HTTP status indicates some kind of error then the exception will tell you what happened. There may be further information in response.text that qualifies the issue.
In this particular example, the HTTP status code is 447 (non-standard) and there’s no other information that explains why that’s been returned. It may simply be because the reference data (json) is garbage
A good practice would be to implement something like the following client:
With this setup you can catch
CustomClientError
at all levels above which is a pretty convenient and scalable way to handle errors.Successful response body can be validated using corresponding
pydantic
model. You can actually even catchpydantic.ValidationError
and convert it toCustomClientError
if you need it.