DEV Community

Cover image for Scraping de legifrance ? Considérez plutôt l'API
Hakim
Hakim

Posted on

4

Scraping de legifrance ? Considérez plutôt l'API

Si vous envisagez le scraping pour récupérer des articles sur le site legifrance vous devriez considérer l'API publique disponible dans le catalogue d'API Piste.

Obtention des identifiants OAuth

Commencez par créer un compte sur Piste.

Capture d'écran du site de Piste, page de création de compte

Ensuite, rendez-vous sous "API > Consentement CGU API" pour accépter les CGU de Légifrance

Capture d'écran du site de Piste, page de consentement CGU

Créez une application dans l'onglet application.

Capture d'écran du site de Piste, page de création d'une application

Une fois créée, modifiez votre application pour y ajouter l'API Légifrance

Capture d'écran du site de Piste, page de mofification des applications
Capture d'écran du site de Piste, page de de mofification des applications, ajout d'une API

De retour dans l'onglet applications, cliquez sur votre application puis récupérer votre client id et votre client secret.

Capture d'écran du site de Piste, page de consultation des applications, récupération des identifiants

Obtention d'un token

L'obtention d'un token se fait via une requête POST sur l'url : https://oauth.piste.gouv.fr/api/oauth/token

Exemple de requête avec cURL :



curl  -X POST \
  'https://oauth.piste.gouv.fr/api/oauth/token' \
  --header 'Accept-Encoding: gzip,deflate' \
  --header 'Content-Type: application/x-www-form-urlencoded' \
  --header 'Content-Length: 140' \
  --data-urlencode 'grant_type=client_credentials' \
  --data-urlencode 'client_id=xxx' \
  --data-urlencode 'client_secret=yyy' \
  --data-urlencode 'scope=openid'


Enter fullscreen mode Exit fullscreen mode

Voici le même exemple sous python :



import requests
from requests_oauthlib import OAuth2Session

client_id = "xxx"
client_secret = "yyy"

res = requests.post(
  "https://oauth.piste.gouv.fr/api/oauth/token",
  data={
    "grant_type": "client_credentials",
    "client_id": client_id,
    "client_secret": client_secret,
    "scope": "openid"
  }
)

res.json()
# {'access_token': 'WxkeizeaK7vqh1A3swGD14RASpM4tTf2PXzC32SV1mzBOebmx1asYA',
#  'token_type': 'Bearer',
#  'expires_in': 3600,
#  'scope': 'openid resource.READ'}


Enter fullscreen mode Exit fullscreen mode

Récupération d'un article à l'aide du token

Le jeton obtenu ci-dessus permet de requête l'API Piste Légifrance.

Voici un exemple avec cURL :



curl  -X POST \
  'https://api.piste.gouv.fr/dila/legifrance/lf-engine-app/consult/getArticle' \
  --header 'Authorization: Bearer k0ESUrVPNCywGOm4Ef9Qehgxj8Ktr4gMhtPNc3DRilz5v11y3JKEDP' \
  --header 'Content-Type: application/json' \
  --data-raw '{
  "id": "LEGIARTI000006307920"
}'


Enter fullscreen mode Exit fullscreen mode

Le même exemple en python :



import requests

response = requests.post(
    "https://api.piste.gouv.fr/dila/legifrance/lf-engine-app/consult/getArticle",
    json={"id": "LEGIARTI000006307920"},
    headers={
        "Authorization": "Bearer k0ESUrVPNCywGOP4Ef9Qehgxj8Ktr4gMhtPNc3DRilz5v11y3JKEDP",
        "Content-Type": "application/json",
    },
)

response.json()
# {
#   "executionTime": 0,
#   "dereferenced": false,
#   "article": {
#     "id": "LEGIARTI000006307920",
#     "idTexte": null,
#     "type": "AUTONOME",
#     "texte": "L'impôt sur le revenu est établi d'après le montant total du revenu net annuel dont dispose chaque foyer fiscal. ..."
#   }
# }


Enter fullscreen mode Exit fullscreen mode

La documentation de l'API est disponible dans le rubrique "API > Mes API" puis en cliquant sur Légifrance.

pylegifrance

Je suis tombé par hasard sur la librairie pylegifrance dont l'objectif est de faciliter la récupération des articles legifrance via l'API de Piste.

Il s'agit plus d'un protoype de librairie puisqu'elle n'est pas encore publiée sur pypi mais a l'air prometteuse donc à surveiller.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay