Khairullin Ramadan
Khairullin Ramadan

Reputation: 1

How to validate company registration data using an API in Python?

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!

Upvotes: 0

Views: 152

Answers (3)

JeeyCi
JeeyCi

Reputation: 597

can process all exceptions in one procedure (or class method) like here

from aiohttp import web
import pydantic

class User(pydantic.BaseModel):
    name: str
    age: int

async def handle_post(request):
    try:
        data = await request.json()
        user = User(**data)
    except (aiohttp.ContentTypeError, pydantic.ValidationError):
        return web.Response(status=400, text="Invalid JSON data") 

    print(f"Created user {user.name} ({user.age})")
    return web.Response(status=201, text="Created user")

app = web.Application()
app.add_routes([web.post('/users', handle_post)])

Upvotes: 0

Victor Egiazarian
Victor Egiazarian

Reputation: 1126

A good practice would be to implement something like the following client:

from contextlib import asynccontextmanager
from typing import AsyncIterator

from aiohttp import ClientResponseError, ClientSession, ClientResponse
from pydantic import BaseModel


class CustomClientError(Exception):
    """Base error for all Client related errors."""


class ValidateCompanyResponse(BaseModel):
    ...


class Client:
    def __init__(self, base_url: str) -> None:
        """."""

        self._session = ClientSession(...)
        self._base_url = base_url


    @asynccontextmanager
    async def handle_client_error(self, response: ClientResponse) -> AsyncIterator[None]:
        """Handle HTTP errors from your Client."""

        try:
            response.raise_for_status()
            yield
        except ClientResponseError as exc:
            logger.error(f"Client error occurred: {exc.message}")
            raise CustomClientError(exc.message)


    async def validate_company(self, data: dict) -> ValidateCompanyResponse:
        """Validate company."""

        async with self._session.post(
            f"{self._base_url}/api/validate",
            json=data,
            headers={"Content-Type": "application/json"},
        ) as response:
            async with self.handle_client_error(response=response):
                company = await response.json()

            return ValidateCompanyResponse.model_validate(company)

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 catch pydantic.ValidationError and convert it to CustomClientError if you need it.

Upvotes: 1

Adon Bilivit
Adon Bilivit

Reputation: 27211

A typical pattern could look like this:

import requests
from requests.exceptions import HTTPError

company_data = {
    "name": "Example Company",
    "registration_number": "123456789",
    "country": "Kazakhstan",
}

url = "https://lcg.kz/api/validate" 

with requests.post(url, json=company_data) as response:
    try:
        response.raise_for_status()
    except HTTPError as e:
        print(e, response.text)

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

Upvotes: 0

Related Questions