Home > Software engineering >  API call - Accessing JSON objects Rails
API call - Accessing JSON objects Rails

Time:05-31

I am trying to call API to query dataset records so user can find a school in my app. Basically i'd like to be able find school name matching with their input. At this stage i have only tried to implemanet API call and save school but i am kinda of stuck now and struggle to access data from Json.

api_schools.rb

require 'uri'
require 'net/http'
require 'openssl'

class ApiSchools

  def call
    set_url
    set_school
    create_school
  end

  def set_url
    @url = URI("https://data.education.gouv.fr/api/records/1.0/search/?dataset=fr-en-annuaire-education")
  end

  def set_school
    http = Net::HTTP.new(@url.host, @url.port)
    http.use_ssl = true

    request = Net::HTTP::Get.new(@url)
    response = http.request(request)
    @schools = JSON.parse(response.read_body)["records"]
    ap @schools
  end

  def create_school
    @schools.each do |school|
      ## set records
      id = school["id"]
      identifiant_de_l_etablissement = school["identifiant_de_l_etablissement"]
      name = school["nom_etablissement"]
      type = school["type_etablissement"]
      status = school["statut_public_prive"]
      nombre_d_eleves = school["nombre_d_eleves"]
      adresse_1 = school["adresse_1"]
      adresse_3 = school["adresse_3"]
      code_postal = school["code_postal"]
      city = school["nom_commune"]
      departement = school["libelle_departement"]
      address = school["voie"]
      email = school["mail"]
      phone = school["telephone"]

      ## Create school
      school =  School.new(id: id, identifiant_de_l_etablissement: identifiant_de_l_etablissement, nom_etablissement: name, type_etablissement: type, statut_public_prive: status, nombre_d_eleves: nombre_d_eleves, adresse_1: adresse_1, adresse_3: adresse_3, code_postal: code_postal, nom_commune: city, libelle_departement: departement, voie: address, mail: email, telephone: phone)
      ap school
      school.save
    end
  end

end

Json


"records":[
{
"datasetid":"fr-en-annuaire-education",
"recordid":"9a1e2add53ae2d5e885c0b478a33134cae58b7c4",
"fields":{
"code_nature":151,
"nom_etablissement":"Ecole primaire Ernest Pérochon",
"nombre_d_eleves":138,
"multi_uai":0,
"type_etablissement":"Ecole",
"code_commune":"79270",
"rpi_concentre":0,
"statut_public_prive":"Public",
"epsg_origine":"EPSG:2154",
"code_academie":"13",
"hebergement":0,
"ulis":0,
"date_ouverture":"1967-08-04",
"identifiant_de_l_etablissement":"0790399E",
"telephone":"0549055362",
"date_maj_ligne":"2022-05-17",
"nom_circonscription":"Circonscription d'inspection du 1er degré de Niort Saint Maixent",
"adresse_1":"Rue de la Gare",
"libelle_region":"Nouvelle-Aquitaine",
"ecole_elementaire":1,
"position":[
46.406925271843825,
-0.20278001351916794
],
"coordx_origine":454027.8,
"precision_localisation":"Numéro de rue",
"libelle_zone_animation_pedagogique":"SUD DEUX-SEVRES",
"longitude":-0.20278001351916794,
"etat":"OUVERT",
"code_departement":"079",
"ecole_maternelle":1,
"adresse_3":"79400 ST MAIXENT L ECOLE",
"restauration":1,
"coordy_origine":6594652.7,
"ministere_tutelle":"MINISTERE DE L'EDUCATION NATIONALE",
"code_zone_animation_pedagogique":"13792",
"code_type_contrat_prive":"99",
"type_contrat_prive":"SANS OBJET",
"libelle_departement":"Deux-Sèvres",
"latitude":46.406925271843825,
"pial":"0790978J",
"siren_siret":"21790270900062",
"code_postal":"79400",
"nom_commune":"Saint-Maixent-l'Ecole",
"libelle_academie":"Poitiers",
"libelle_nature":"ECOLE DE NIVEAU ELEMENTAIRE",
"code_region":"75",
"mail":"[email protected]"
},
"geometry":{
"type":"Point",
"coordinates":[
-0.20278001351916794,
46.406925271843825
]
},
"record_timestamp":"2022-05-17T16:04:00Z"
},
irb(main):001:0> ApiSchools.new.call
    [0] {
               "datasetid" => "fr-en-annuaire-education",
                "recordid" => "7c3fb5e473a93b3858fe6e57deb8c38b5ee5c35a",
                  "fields" => {
                               "code_nature" => 151,
                         "nom_etablissement" => "Ecole élémentaire Albert PERRAUD",
                                 "multi_uai" => 0,
                        "type_etablissement" => "Ecole",
                              "code_commune" => "98818",
                             "rpi_concentre" => 0,
                       "statut_public_prive" => "Public",
                             "code_academie" => "40",
                               "hebergement" => 0,
                                      "ulis" => 0,
                            "date_ouverture" => "1994-03-01",
            "identifiant_de_l_etablissement" => "9830505G",
                                 "telephone" => "0687240624",
                            "date_maj_ligne" => "2022-05-17",
                       "nom_circonscription" => "Circonscription d'inspection du 1er degré de Nouméa - I.E.P. 1ère circonscription",
                                 "adresse_1" => "11  RUE DE TIGA MAGENTA",
                            "libelle_region" => "TOM et Collectivités territoriales",
                         "ecole_elementaire" => 1,
                                      "etat" => "OUVERT",
                          "code_departement" => "988",
                          "ecole_maternelle" => 0,
                                 "adresse_2" => "BP 14372",
                                 "adresse_3" => "98803 NOUMEA CEDEX",
                              "restauration" => 0,
                         "ministere_tutelle" => "MINISTERE DE L'EDUCATION NATIONALE",
                   "code_type_contrat_prive" => "99",
                        "type_contrat_prive" => "SANS OBJET",
                       "libelle_departement" => "Nouvelle Calédonie",
                               "siren_siret" => "20001250800327",
                               "code_postal" => "98803",
                               "nom_commune" => "Nouméa",
                          "libelle_academie" => "Nouvelle Calédonie",
                            "libelle_nature" => "ECOLE DE NIVEAU ELEMENTAIRE",
                               "code_region" => "00",
                                      "mail" => "[email protected]"
        },
        "record_timestamp" => "2022-05-17T16:04:00Z"
    },
 
]
#<School:0x00007fda2033a728> {
                                :id => nil,
    :identifiant_de_l_etablissement => nil,
                 :nom_etablissement => nil,
                :type_etablissement => nil,
               :statut_public_prive => nil,
                   :nombre_d_eleves => nil,
                         :adresse_1 => nil,
                         :adresse_3 => nil,
                       :code_postal => nil,
                       :nom_commune => nil,
               :libelle_departement => nil,
                              :voie => nil,
                              :mail => nil,
                         :telephone => nil,
                               :lab => nil,
                        :created_at => nil,
                        :updated_at => nil

Any help is appreciated.

Thank you

CodePudding user response:

I would suggest to change key names to match your database table schools and then bulk the whole json into the database with insert_all.

CodePudding user response:

After parsing the result you received from the URL:

  • api_schools.rb (line 23)
@schools = JSON.parse(response.read_body)["records"]

you will end up with a nested hash that looks like this:

[{datasetid:"..",...},{"datasetid":"...",...},...]

In your create_schools method, when you iterate over @schools, outputting the current item to the console

  • api_schools.rb (line 28)
@schools.each do |school|
  puts school
  break
  ## set records
  ...
end

will show you the first item of the array, that looks like this:

{
   "datasetid""=>""fr-en-annuaire-education",
   "recordid""=>""1f459a0053d4c075a56d5d81a96d4a4acc0ba963",
   "fields""=>"{
      "code_nature"=>151,
      "nom_etablissement""=>""Ecole élémentaire Guillaumes",
      "nombre_d_eleves"=>27,
      "multi_uai"=>0,
      "type_etablissement""=>""Ecole",
      "code_commune""=>""06071",
      "rpi_concentre"=>0,
      "statut_public_prive""=>""Public",
      "epsg_origine""=>""EPSG:2154",
      "code_academie""=>""23",
      "hebergement"=>0,
      "ulis"=>0,
      "date_ouverture""=>""1965-07-05",
      "identifiant_de_l_etablissement""=>""0060285C",
      "telephone""=>""0493055087",
      "date_maj_ligne""=>""2022-05-29",
      "nom_circonscription""=>""Circonscription d'inspection du 1er degré de Carros 3 Vallées",
      "adresse_1""=>""Place de Provence",
      "libelle_region""=>""Provence-Alpes-Côte d'Azur",
      "ecole_elementaire"=>1,
      "position""=>"[
         44.08959199032698,
         6.853710118930262
      ],
      "coordx_origine"=>1008483.1,
      "precision_localisation""=>""Numéro de rue",
      "libelle_zone_animation_pedagogique""=>""NICE TROIS VALLEES",
      "longitude"=>6.853710118930262,
      "etat""=>""OUVERT",
      "code_departement""=>""006",
      "ecole_maternelle"=>1,
      "adresse_3""=>""06470 GUILLAUMES",
      "restauration"=>0,
      "coordy_origine"=>6339816.8,
      "ministere_tutelle""=>""MINISTERE DE L'EDUCATION NATIONALE",
      "code_zone_animation_pedagogique""=>""23063",
      "code_type_contrat_prive""=>""99",
      "type_contrat_prive""=>""SANS OBJET",
      "libelle_departement""=>""Alpes-Maritimes",
      "latitude"=>44.08959199032698,
      "pial""=>""0060066P",
      "siren_siret""=>""21060071400021",
      "code_postal""=>""06470",
      "nom_commune""=>""Guillaumes",
      "libelle_academie""=>""Nice",
      "libelle_nature""=>""ECOLE DE NIVEAU ELEMENTAIRE",
      "code_region""=>""93",
      "mail""=>""[email protected]"
   },
   "geometry""=>"{
      "type""=>""Point",
      "coordinates""=>"[
         6.853710118930262,
         44.08959199032698
      ]
   },
   "record_timestamp""=>""2022-05-30T02:00:00Z"
}

Most of the fields you want to assign in create_school are nested under school["fields"]. If you want to for example get the value of nom_etablissement you can get the value using respective hash keys:

  • api_schools.rb:32
name = school["fields"]["nom_etablissement"]
puts name

#> "Ecole"

Here is a nice article that explains in a little more detail how nested hashes can be instantiated and accessed.

Happy coding!

  • Related