Home > Software design >  How to return a list with a certain parameter from an API?
How to return a list with a certain parameter from an API?

Time:11-24

I need to return a list with the the title ("titulo") of the news that appear in this api: https://www.publico.pt/api/list/ultimas

I tried this but it only returns the title of the title (titulo) of the first new and not all the titles.

import requests

def get_news():
    
    url = "https://www.publico.pt/api/list/ultimas"

    response = requests.get(url)
    data = response.json()  
    for news in data:
        titulo = [news["titulo"]]  
        
        return titulo
    
print(get_news())

CodePudding user response:

i think this might be what you actually want to do:

url = "https://www.publico.pt/api/list/ultimas"

response = requests.get(url)
data = response.json()
titulo = []
for news in data:    
    titulo.append(news["titulo"])  
    
return titulo

this puts all the data into a list and returns the list.

  • Related