All guides
Intermediate-AdvancedSelf-pacedFree GuideSection 9/33

Parsing et consommation d'API

Learn to build and check a web application with development tools and AI assistants. Practise design, coding and validation.

The full lessons for this course are currently available in French. Use the section menu to navigate the French course.

💡

Free content, available without an account. Tools and models change: use the current model guide to check their versions. Models and sources

Section 13.2.4 : Parsing et consommation d'API

🎯 Objectif pédagogique

Lire des fichiers structurés (CSV, JSON) et consommer des APIs REST en Ruby — compétences essentielles pour des applications connectées.


Parsing CSV

require 'csv'

CSV.foreach('clients.csv', headers: true) do |row|
  puts "#{row['nom']} - #{row['email']}"
end

# Écrire un CSV
CSV.open('export.csv', 'w') do |csv|
  csv << ['nom', 'email', 'age']
  csv << ['Alice', 'alice@test.com', 28]
  csv << ['Bob', 'bob@test.com', 32]
end

Parsing JSON

require 'json'

json_string = '{"nom": "Alice", "age": 28}'
data = JSON.parse(json_string)
data['nom']

# Avec clés symboliques
data = JSON.parse(json_string, symbolize_names: true)
data[:nom]

# Générer du JSON
utilisateur = { nom: 'Alice', age: 28 }
JSON.generate(utilisateur)
JSON.pretty_generate(utilisateur)

Consommer une API REST

require 'open-uri'
require 'json'

url = 'https://api.github.com/users/lewagon'
response = URI.open(url).read
user = JSON.parse(response)
puts user['name']
puts user['public_repos']

La gem rest-client

require 'rest-client'
require 'json'

# GET
response = RestClient.get('https://api.example.com/users')
users = JSON.parse(response.body)

# POST
response = RestClient.post(
  'https://api.example.com/users',
  { nom: 'Alice', email: 'alice@test.com' }.to_json,
  { content_type: :json, accept: :json }
)

# Gestion d erreurs
begin
  RestClient.get('https://api.example.com/unknown')
rescue RestClient::NotFound
  puts '404 - Non trouvé'
rescue RestClient::ExceptionWithResponse => e
  puts "Erreur: #{e.response.code}"
end

Exercice : CLI météo

require 'open-uri'
require 'json'

class MeteoService
  BASE_URL = 'https://api.open-meteo.com/v1/forecast'

  def temperature(lat, lon)
    url = "#{BASE_URL}?latitude=#{lat}&longitude=#{lon}&current_weather=true"
    data = JSON.parse(URI.open(url).read)
    data['current_weather']['temperature']
  end
end

service = MeteoService.new
temp = service.temperature(48.8566, 2.3522)
puts "Paris : #{temp} C"
Quick Check

Quelle méthode convertit un Hash Ruby en JSON ?

Learn AI, from prompts to agents

15 free guidesQuizzes, diagrams and workshopsNo account needed

Your progress

Progress is self-reported and stored in your browser. The final completion record is not a qualification or an independent assessment.

View progress and completion record

Learn AI, from prompts to agents

15 free guidesQuizzes, diagrams and workshopsNo account needed

One practical AI workflow in your inbox

Methods, resources and new exercises. Free, unsubscribe at any time.