Skip to content

Commit c3b17b6

Browse files
author
Your Name
committed
f
0 parents  commit c3b17b6

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
f

main_02_requests.py

Whitespace-only changes.

task_02_requests.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import requests
2+
import csv
3+
4+
# Fonction pour récupérer et afficher les posts
5+
def fetch_and_print_posts():
6+
response = requests.get('https://jsonplaceholder.typicode.com/posts')
7+
print("Status Code:", response.status_code)
8+
9+
if response.status_code == 200:
10+
data = response.json()
11+
for post in data:
12+
print(post['title'])
13+
else:
14+
print("Request failed!")
15+
16+
# Fonction pour récupérer, structurer et sauvegarder les posts dans un CSV
17+
def fetch_and_save_posts():
18+
response = requests.get('https://jsonplaceholder.typicode.com/posts')
19+
20+
if response.status_code == 200:
21+
data = response.json()
22+
23+
structured_data = []
24+
for post in data:
25+
structured_data.append({
26+
"id": post['id'],
27+
"title": post['title'],
28+
"body": post['body']
29+
})
30+
31+
# Écrire les données dans un fichier CSV
32+
with open('posts.csv', 'w', newline='', encoding='utf-8') as csvfile:
33+
fieldnames = ['id', 'title', 'body']
34+
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
35+
36+
writer.writeheader() # Écrire l'en-tête
37+
writer.writerows(structured_data) # Écrire les données
38+
39+
print("Posts saved to posts.csv successfully!")
40+
else:
41+
print("Request failed!")
42+

0 commit comments

Comments
 (0)