api.automapa.comv3 - all systems normal
Code examples

Native AutoMapa SDK: PHP and Python

Install pinned AutoMapa SDK sources, geocode an address, reverse geocode coordinates and handle results and errors in PHP and Python.

geocode returns result as a list; this example reads its first match and quality. x is longitude and y is latitude. revgeocode takes [longitude, latitude] and returns an address object, which need not contain coordinates. pcode can be null even when requested. raw() preserves the response envelope; native data() normally exposes result. The examples use raw() to handle a null result consistently in both SDKs. Snapping to a building is best effort and does not guarantee a house number; forward and reverse geocoding need not be exact inverses. For international reverse geocoding, omit params. The PHP SDK wrapper always includes it, so use a direct REST call. Python omits it when no reverse-geocoding flags are supplied.

The pinned PHP/Python geocode wrappers send top-level maxResults (Python argument max_results), which REST ignores. The Google adapter always adds maxResults=1; this does not set the server limit. Known arguments overwrite extra.address, so extra.address.maxResult does not fix the wrapper. To set the limit, call POST /v3/Geocoder/geocode directly with {"address":{"city":"Nowa Wieś","maxResult":3}}; for geocodemulti put maxResult in each address. Native examples omit the wrapper option. The SDK requires a city argument; the public REST geocoding contract also requires city in every address. For PL addresses, address.maxResult is 1–3 (default 1).

Geocoder.geocode · Geocoder.revgeocode

Read results and handle errors

An empty or null result is handled separately from an exception. NO_RESULTS is a label defined by these examples, not an API status. Catch SDK exceptions for HTTP, transport or decoding failures; SESSION_REQUIRED means your integration must provide a fresh session. The command-line entry points report a generic error without logging response bodies or sessions. Add your application’s error handling before integration.

PHP requires PHP 8.0 or later, Composer, ext-curl and ext-json. Python requires Python 3.11 or later and pip. Run the commands for your language in a terminal; the examples run on your server.

Pinned source snapshots; links point to the exact commits used by these examples.

Save the bootstrap and example files below in the SDK repository directory created during installation, using the displayed filenames. Both paths use the same bootstrap. The .txt downloads contain source code; remove .txt when saving.

PHP

automapa-map-services-php
81d5014db53d5da37a121d335adc55b4c23c2818

1. Install pinned sources

git clone https://github.com/automapa/automapa-map-services-php.git
cd automapa-map-services-php
git checkout --detach 81d5014db53d5da37a121d335adc55b4c23c2818
composer install --no-dev

2. Bootstrap with a supplied session

Obtain a valid AutoMapa session through your server-side authentication integration (see the authentication guide) and provide it as AUTOMAPA_SESSION_ID in the process environment. Keep it out of source control, browser code and logs. SuppliedSession below is application code implementing the SDK storage interface. Empty Config credentials are deliberate: get() throws when the supplied session is missing or cleared after HTTP 403, preventing the SDK from starting its automatic handshake. Obtain a new session through your integration and rebuild the client to retry.

Authentication

bootstrap.php

Download source — bootstrap.php

<?php
declare(strict_types=1);
require_once __DIR__ . '/vendor/autoload.php';

use Automapa\MapServices\ApiClient;
use Automapa\MapServices\Config;
use Automapa\MapServices\Http\CurlHttpClient;
use Automapa\MapServices\Http\HttpClientInterface;
use Automapa\MapServices\Session\SessionManager;
use Automapa\MapServices\Session\SessionStorage;

final class SuppliedSession implements SessionStorage
{
    public function __construct(private string $sessionId) {}

    public function get(): ?string
    {
        if ($this->sessionId === '') {
            throw new RuntimeException('SESSION_REQUIRED');
        }
        return $this->sessionId;
    }

    public function store(string $sessionId): void
    {
        $this->sessionId = $sessionId;
    }

    public function clear(): void
    {
        $this->sessionId = '';
    }
}

function buildClient(string $sessionId, ?HttpClientInterface $http = null): ApiClient
{
    $storage = new SuppliedSession($sessionId);
    $storage->get();
    $config = new Config(key: '', pass: '', baseUrl: 'https://api.automapa.com/');
    $http ??= new CurlHttpClient();
    return new ApiClient($config, $http, new SessionManager($config, $http, $storage));
}

3. Run the example

native.php

Download source — native.php

<?php
declare(strict_types=1);
require_once __DIR__ . '/bootstrap.php';

use Automapa\MapServices\ApiClient;
use Automapa\MapServices\Exception\AutomapaException;

function geocode(ApiClient $client): array
{
    $response = $client->geocoder()->geocode(
        city: 'Warszawa', street: 'Domaniewska', house: '37', country: 'PL'
    );
    $matches = $response->raw()['result'] ?? [];
    if ($matches === []) {
        return ['status' => 'NO_RESULTS'];
    }
    if (!is_array($matches) || !isset($matches[0])) {
        throw new RuntimeException('UNEXPECTED_RESULT');
    }
    $first = $matches[0];
    return ['status' => 'OK', 'lng' => $first['x'] ?? null, 'lat' => $first['y'] ?? null,
        'city' => $first['city'] ?? null, 'quality' => $first['quality'] ?? null];
}

function revgeocode(ApiClient $client): array
{
    $response = $client->geocoder()->revgeocode(
        point: [21.0065983, 52.1832837], getPostalCode: true
    );
    $address = $response->raw()['result'] ?? [];
    if (!$address) {
        return ['status' => 'NO_RESULTS'];
    }
    if (!is_array($address)) {
        throw new RuntimeException('UNEXPECTED_RESULT');
    }
    return ['status' => 'OK', 'city' => $address['city'] ?? null,
        'street' => $address['street'] ?? null, 'house' => $address['house'] ?? null,
        'pcode' => $address['pcode'] ?? null];
}

if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) {
    try {
        $client = buildClient(getenv('AUTOMAPA_SESSION_ID') ?: '');
        echo json_encode(['geocode' => geocode($client), 'revgeocode' => revgeocode($client)]);
    } catch (AutomapaException | RuntimeException $error) {
        fwrite(STDERR, "SDK_ERROR_OR_SESSION_REQUIRED\n");
        exit(1);
    }
}
php native.php

Python

automapa-map-services-python
bdc98c1778d78d11a170b02dd050e89fef9247ba

1. Install pinned sources

git clone https://github.com/automapa/automapa-map-services-python.git
cd automapa-map-services-python
git checkout --detach bdc98c1778d78d11a170b02dd050e89fef9247ba
python3 -m venv .venv
. .venv/bin/activate
python -m pip install .

2. Bootstrap with a supplied session

Obtain a valid AutoMapa session through your server-side authentication integration (see the authentication guide) and provide it as AUTOMAPA_SESSION_ID in the process environment. Keep it out of source control, browser code and logs. SuppliedSession below is application code implementing the SDK storage interface. Empty Config credentials are deliberate: get() throws when the supplied session is missing or cleared after HTTP 403, preventing the SDK from starting its automatic handshake. Obtain a new session through your integration and rebuild the client to retry.

Authentication

bootstrap.py

Download source — bootstrap.py

from automapa_map_services.client import ApiClient
from automapa_map_services.config import Config
from automapa_map_services.http.urllib_client import UrllibHttpClient
from automapa_map_services.session.manager import SessionManager


class SuppliedSession:
    def __init__(self, session_id: str):
        self.session_id = session_id

    def get(self) -> str:
        if not self.session_id:
            raise RuntimeError("SESSION_REQUIRED")
        return self.session_id

    def store(self, session_id: str) -> None:
        self.session_id = session_id

    def clear(self) -> None:
        self.session_id = ""


def build_client(session_id: str, http_client=None) -> ApiClient:
    storage = SuppliedSession(session_id)
    storage.get()
    config = Config(key="", password="", base_url="https://api.automapa.com/")
    http = http_client if http_client is not None else UrllibHttpClient()
    return ApiClient(config, http, SessionManager(config, http, storage))

3. Run the example

native.py

Download source — native.py

import json
import os
from bootstrap import build_client
from automapa_map_services.exceptions import AutomapaException


def geocode(client):
    response = client.geocoder().geocode(
        city="Warszawa", street="Domaniewska", house="37", country="PL"
    )
    matches = response.raw().get("result")
    if matches is None or matches == []:
        return {"status": "NO_RESULTS"}
    if not isinstance(matches, list):
        raise RuntimeError("UNEXPECTED_RESULT")
    first = matches[0]
    return {"status": "OK", "lng": first.get("x"), "lat": first.get("y"),
            "city": first.get("city"), "quality": first.get("quality")}


def revgeocode(client):
    response = client.geocoder().revgeocode(
        point=[21.0065983, 52.1832837], get_postal_code=True
    )
    address = response.raw().get("result")
    if not address:
        return {"status": "NO_RESULTS"}
    if not isinstance(address, dict):
        raise RuntimeError("UNEXPECTED_RESULT")
    return {"status": "OK", "city": address.get("city"),
            "street": address.get("street"), "house": address.get("house"),
            "pcode": address.get("pcode")}


if __name__ == "__main__":
    try:
        client = build_client(os.environ.get("AUTOMAPA_SESSION_ID", ""))
        print(json.dumps({"geocode": geocode(client), "revgeocode": revgeocode(client)}))
    except (AutomapaException, RuntimeError):
        raise SystemExit("SDK_ERROR_OR_SESSION_REQUIRED")
python native.py