API-INSEE-Sirene

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

        - Fixed typing errors

4.03
        - Removed unused import
        - Updated README
        - Updated documentation

4.02
        - The getCustomCriteria method doesn't take $use_historized_field parameter anymore
          The module will now auto-detect historized fields
        - Added setCurrentEndpoint method
        - Aliases are now mapped with more fields
        - Updated documentation

4.01
        - Updated dependencies in Makefile.PL

4.00
        - Major internal restructuration
        - The module version number is no longer depending on the INSEE's API version number
        - The module is now using OOP
        - The module will now send requests using POST method when possible.
            This is allowed by the INSEE's API since version 3.6.0 in order to avoid too long requests in the URL.
        - The API returns HTTP_NOT_FOUND code when no results have been found, even if the request was correct.
            The module now handles this case correctly and returns the json body instead of dumping the request.
        - In general way, the module now correctly handles the different HTTP response codes given by the API
        - Better handling of tokens renewal
        - Added searchLegalUnitBySIREN method
        - Added searchEstablishmentBySIRET method
        - Added getCustomCriteria method
        - Added searchByCustomCriteria method
        - Added setMaxResults method
        - Added setDebugMode method
        - Added setProxy method
        - Added setTimeout method
        - Added setCredentials method
        - Added MIN_DIGIT constant 
        - Removed CLIENT_AUTH constant
        - Removed getEstablishmentsByCriteria function
        - Removed getLegalUnitsByCriteria function
        - Removed getUserAgentInitialized function
        - Updated documentation

3.507
        - Updated documentation

lib/API/INSEE/Sirene.pm  view on Meta::CPAN

    my $self = bless {
        credentials      => $credentials,
        user_agent       => undef,
        token_expiration => undef,
        max_results      => undef,
        debug_mode       => 0,
        current_endpoint => undef,
    }, $class;

    $self->_initUserAgent();
    $self->setProxy($proxy);
    $self->setMaxResults($max_results);
    $self->setTimeout($timeout);

    return $self;
}

sub setCredentials {
    my ($self, $credentials) = @_;

    $self->{'credentials'} = $credentials;
}

sub setMaxResults {
    my ($self, $max_results) = @_;

    $max_results //= DEFAULT_MAX_RESULTS;
    $self->{'max_results'} = $max_results > HARD_MAX_RESULTS ? HARD_MAX_RESULTS : $max_results;
}

sub setDebugMode {
    my ($self, $debug_value) = @_;

    $self->{'debug_mode'} = $debug_value;
}

sub setProxy {
    my ($self, $proxy) = @_;

    defined $proxy ? $self->{'user_agent'}->proxy([ 'http', 'https' ], $proxy) : $self->{'user_agent'}->env_proxy;
}

sub setTimeout {
    my ($self, $timeout) = @_;

    $timeout //= DEFAULT_TIMEOUT;
    $self->{'user_agent'}->timeout($timeout);
}

sub setCurrentEndpoint {
    my ($self, $endpoint) = @_;

    $self->{'current_endpoint'} = $endpoint;
}

sub _dumpRequest {
    my ($self, $request, $response) = @_;

    my $dump = sprintf "Sent request:\n%s\n", $request->as_string;
    $dump .= sprintf "Received response:\n%s\n", $response->as_string if defined $response;

lib/API/INSEE/Sirene.pm  view on Meta::CPAN


    return $self->_sendRequest($parameters);
}

sub getLegalUnitBySIREN {
    my ($self, $siren_number, $desired_fields) = @_;

    return 1, "Invalid SIREN $siren_number -> Must be a ${ \MAX_SIREN_LENGTH } digits number."
        if $siren_number !~ m/^\d{${ \MAX_SIREN_LENGTH }}$/;

    $self->setCurrentEndpoint("siren/$siren_number");
    my $parameters = $self->_buildParameters($useful_fields_legal_unit, $desired_fields);

    return $self->_sendRequest($parameters);
}

sub searchLegalUnitBySIREN {
    my ($self, $siren_number, $desired_fields) = @_;

    return 1, "Invalid SIREN $siren_number -> Must be a ${ \MIN_LENGTH } digits min and ${ \MAX_SIREN_LENGTH } digits number max."
        if $siren_number !~ m/^\d{${ \MIN_LENGTH },${ \MAX_SIREN_LENGTH }}$/;

    $self->setCurrentEndpoint('siren');
    my $criteria = $self->getCustomCriteria('siren', $siren_number, 'begin');

    return $self->searchByCustomCriteria($criteria, $desired_fields);
}

sub getEstablishmentBySIRET {
    my ($self, $siret_number, $desired_fields) = @_;

    return 1, "Invalid SIRET $siret_number -> Must be a ${ \MAX_SIRET_LENGTH } digits number."
        if $siret_number !~ m/^\d{${ \MAX_SIRET_LENGTH }}$/;

    $self->setCurrentEndpoint("siret/$siret_number");
    my $parameters = $self->_buildParameters($useful_fields_establishment, $desired_fields);

    return $self->_sendRequest($parameters);
}

sub getEstablishmentsBySIREN {
    my ($self, $siren_number, $desired_fields) = @_;

    return (1, "Invalid SIREN $siren_number -> Must be a ${ \MAX_SIREN_LENGTH } digits number.")
        if $siren_number !~ m/^\d{${ \MAX_SIREN_LENGTH }}$/;

    $self->setCurrentEndpoint('siret');
    my $criteria = $self->getCustomCriteria('siren', $siren_number);

    return $self->searchByCustomCriteria($criteria, $desired_fields);
}

sub searchEstablishmentBySIRET {
    my ($self, $siret_number, $desired_fields) = @_;

    return 1, "Invalid SIRET $siret_number -> Must be a ${ \MIN_LENGTH } digits min and a ${ \MAX_SIRET_LENGTH } digits number max."
        if $siret_number !~ m/^\d{${ \MIN_LENGTH },${ \MAX_SIRET_LENGTH }}$/;

    $self->setCurrentEndpoint('siret');
    my $criteria = $self->getCustomCriteria('siret', $siret_number);

    return $self->searchByCustomCriteria($criteria, $desired_fields);
}

sub getLegalUnitsByName {
    my ($self, $name, $desired_fields) = @_;

    $self->setCurrentEndpoint('siren');
    my $criteria = $self->getCustomCriteria('denominationUniteLegale', $name);

    return $self->searchByCustomCriteria($criteria, $desired_fields);
}

sub getEstablishmentsByName {
    my ($self, $name, $desired_fields) = @_;

    $self->setCurrentEndpoint('siret');
    my $criteria = $self->getCustomCriteria('denominationUniteLegale', $name);

    return $self->searchByCustomCriteria($criteria, $desired_fields);
}

sub getLegalUnitsByUsualName {
    my ($self, $name, $desired_fields) = @_;


    $self->setCurrentEndpoint('siren');
    my $criteria = $self->getCustomCriteria('denominationUsuelle1UniteLegale', $name);

    return $self->searchByCustomCriteria($criteria, $desired_fields);
}

sub getEstablishmentsByUsualName {
    my ($self, $name, $desired_fields) = @_;

    $self->setCurrentEndpoint('siret');
    my $criteria = $self->getCustomCriteria('denominationUsuelle1UniteLegale', $name);

    return $self->searchByCustomCriteria($criteria, $desired_fields);
}

1;

__END__

=pod

lib/API/INSEE/Sirene.pm  view on Meta::CPAN


=head1 VERSION

Version 4.04

=head1 SYNOPSIS

  use API::INSEE::Sirene;

  my $sirene = API::INSEE::Sirene->new('Y29uc3VtZXIta2V5OmNvbnN1bWVyLXNlY3JldA=='); # your base64 encoded credentials
  $sirene->setMaxResults(30);

  # Examples to get information about an establishment with SIRET number '12345678987654'
  $sirene->getEstablishmentBySIRET(12345678987654, 'all');

  # or
  my $fields_that_interest_me = ['numeroVoieEtablissement', 'typeVoieEtablissement', 'libelleVoieEtablissement',
                                 'codePostalEtablissement', 'libelleCommuneEtablissement'];
  $sirene->getEstablishmentBySIRET(12345678987654, $fields_that_interest_me);

  # or

lib/API/INSEE/Sirene.pm  view on Meta::CPAN

  $sirene->getEstablishmentBySIRET(12345678987654);

  # you can also perform searches whith a partial SIREN/SIRET number using search functions:
  $sirene->searchEstablishmentBySIRET(1234567898);
  $sirene->searchLegalUnitBySIREN(123456);

=head1 DESCRIPTION

This module allows you to interact with the Sirene API of INSEE (Institut National de la Statistique et des Études Économiques) in France.

It contains a set of functions that can perform searches on INSEE's database to get some information about french companies like their SIREN number, company name, company headquarters address, etc.

The terms "enterprise", "legal unit" and "establishment" used in this documentation are defined at the INSEE website in the following pages:

=over 4

=item * B<Enterprise definition:>

L<< https://www.insee.fr/en/metadonnees/definition/c1496 >>

=item * B<Legal unit definition:>

lib/API/INSEE/Sirene.pm  view on Meta::CPAN

=item * L<< POSIX::strftime|https://metacpan.org/pod/POSIX#strftime >>

=item * L<< Switch|https://metacpan.org/pod/Switch >>

=back

=head1 CONSTANTS

=head2 DEFAULT_MAX_RESULTS

The API's default number of results for each request. You can override it with the C<< setMaxResults >> method. A too big value may impact response time and general performances.

This constant is set to 20 results.

=head2 DEFAULT_TIMEOUT

This constant specifies how many seconds the client module has to wait for server response before giving up. You can override it with the C<< setTimeout >> method.

This constant is set to 20 seconds.

=head2 HARD_MAX_RESULTS

The maximum number of results that you can get. This value can't be increased (restricted by API). If you try to send a request with a higher value, the C<nombre> parameter will be forced to HARD_MAX_RESULTS value.

This constant is set to 1000 results.

=head2 MAX_SIREN_LENGTH

A SIREN number has a maximum length of 9 digits.

=head2 MAX_SIRET_LENGTH

A SIREN number has a maximum length of 14 digits.

=head2 MIN_LENGTH

lib/API/INSEE/Sirene.pm  view on Meta::CPAN

=head2 getCustomCriteria

You can use this method to build more specific criteria:

  my $criteria1 = $sirene->getCustomCriteria('numeroVoieEtablissement', 42);

You can choose between three search modes: 'exact', 'begin' or 'approximate' match. Default is 'approximate'.

  my $criteria2 = $sirene->getCustomCriteria('libelleVoieEtablissement', 'avenue', undef, 'exact');

B<< Important: >> You must specify the endpoint to be reached B<< before >> calling the C<< getCustomCriteria >> method using C<< setCurrentEndpoint >>

  $sirene->setCurrentEndpoint('siret');

=head2 getEstablishmentsByName

Search all establishments matching the specified name. (denominationUniteLegale field)

=head2 getEstablishmentsBySIREN

Search all the establishments attached to a legal unit identified by a SIREN number.

=head2 getEstablishmentBySIRET

lib/API/INSEE/Sirene.pm  view on Meta::CPAN

Search all legal units matching the specified name. (denominationUsuelle1UniteLegale field)

=head2 getLegalUnitBySIREN

Search a legal unit by its SIREN number.

=head2 searchByCustomCriteria

This method is used to perform a search with a custom criteria built using the C<< getCustomCriteria >> method.

Before using this method, you have to specify the targeted endpoint by calling the C<< setCurrentEndpoint >> method.

  my $final_criteria = "$criteria1 OR $criteria2";
  my ($err, $result) = $sirene->$sirene->searchByCustomCriteria($final_criteria);

=head2 searchEstablishmentBySIRET

Search all establishments which SIRET number is begining by the number given in parameter.

=head2 searchLegalUnitBySIREN

Search all legal units which SIREN number is begining by the number given in parameter.

=head2 setCredentials

You can set your credentials separately from the instantiation if you need to (but this must be done before any call to the search methods).

  $sirene->setCredentials('Y29uc3VtZXIta2V5OmNvbnN1bWVyLXNlY3JldA==');

=head2 setCurrentEndpoint

Used to specifie the reached API endpoint.

=head2 setDebugMode

Enables the debug mode. When enabled, all the requests built by the module are displayed instead of being sent.

  $sirene->setDebugMode(1);

=head2 setMaxResults

Used to override the B<< DEFAULT_MAX_RESULTS >> value to get more results, within the limit of B<< HARD_MAX_RESULTS >> value.

  $sirene->setMaxResults(30);

=head2 setProxy

You can define which proxy server must be used to send requests. The system's proxy settings are used by default.

  $sirene->setProxy('https://myproxy.com:1234');

=head2 setTimeout

Used to override the B<< DEFAULT_TIMEOUT >> value.

  $sirene->setTimeout(40);

=head1 PARAMETERS

All search methods take an optional C<< $desired_fields >> parameter that comes in three differents flavours:

  my $fields_that_interest_me = ['dateCreationUniteLegale', 'sigleUniteLegale'];
  my $response_json = $sirene->getLegalUnitBySIREN(123456789, $fields_that_interest_me);

  # or
  my $response_json = $sirene->getLegalUnitBySIREN(123456789, 'dateCreationUniteLegale');

t/API-INSEE-Sirene.t  view on Meta::CPAN

use strict;
use warnings;

use Test::More;
use HTTP::Request;

BEGIN { use_ok('API::INSEE::Sirene') };

my $sirene = API::INSEE::Sirene->new('fake_credential');

$sirene->setCurrentEndpoint('siren');
my @oks_custom_criteria = (
#   [ expected_result, field_name, value ... ],
    [ '(siret:"12345678901234"~ OR siret:*12345678901234*)',                'siret',                   '12345678901234',         ],
    [ '(siret:"12345678901234"~ OR siret:*12345678901234*)',                'siret',                   '12345678901234',         ],
    [ 'periode(nomUniteLegale:"foo"~ OR nomUniteLegale:*foo*)',             'nomUniteLegale',          'foo',                    ],
    [ 'periode(nomUniteLegale:"foo%26bar"~ OR nomUniteLegale:*foo%26bar*)', 'nomUniteLegale',          'foo&bar',                ],
    [ 'periode(nomUniteLegale:foo)',                                        'nomUniteLegale',          'foo',            'exact' ],
    [ 'periode(nomUniteLegale:foo*)',                                       'nomUniteLegale',          'foo',            'begin' ],
    [ 'libelleVoieEtablissement:foo',                                       'nomvoie',                 'foo',            'exact' ],
    [ 'periode(denominationUniteLegale:foo)',                               'denominationUniteLegale', 'foo',            'exact' ],
    [ 'periode(denominationUniteLegale:bar*)',                              'denominationUniteLegale', 'bar',            'begin' ],
    [ 'periode(denominationUniteLegale:foo%26bar)',                         'denominationUniteLegale', 'foo&bar',        'exact' ],
    [ 'adresseEtablissement:foo',                                           'adresseEtablissement',    'foo',            'exact' ],
);

foreach (@oks_custom_criteria) {
    my ($expected, @args) = @{ $_ };
    ok($expected eq $sirene->getCustomCriteria(@args));
}

$sirene->setDebugMode(1);

my @oks_request_GET = (
    [ 'getLegalUnitBySIREN',     '123456789'      ],
    [ 'getEstablishmentBySIRET', '12345678901234' ],
);

foreach (@oks_request_GET) {
    my ($method, @args) = @{$_};

    can_ok($sirene, $method);



( run in 0.965 second using v1.01-cache-2.11-cpan-49f99fa48dc )