Search code examples
pythonpython-3.xnewsapi

newsAPI import error cannot import name 'NewsApiClient' from 'newsapi'


i wanted to make a program for news using the NewsApi.org Api, but i've got a problem i dont know how to solve. my code is:

import requests
from newsapi import NewsApiClient

url = ('https://newsapi.org/v2/everything?'
       'q=Apple&'
       'from=2023-06-11&'
       'sortBy=popularity&'
       'apiKey=0e24ed7870d04cc392d0a5804381faf7')

response = requests.get(url)
r = 0
print (r.json)

and the error im getting is: ImportError: cannot import name 'NewsApiClient' from 'newsapi' (c:\Users\tomh2\Desktop\newsapi.py)

(whole error)

Traceback (most recent call last): File "c:\Users\tomh2\Desktop\news.py", line 2, in from newsapi import NewsApiClient ImportError: cannot import name 'NewsApiClient' from 'newsapi' (c:\Users\tomh2\Desktop\newsapi.py)

i hoped to get the latest apple news, but just got this error!


Solution

  • Your main script (c:\Users\tomh2\Desktop\news.py) cannot import NewsApiClient. It seems that you do not even need this class, as it is not used in your main script. Change the code of your news.py as follows:

    import requests
    
    url = ('https://newsapi.org/v2/everything?'
           'q=Apple&'
           'from=2023-06-11&'
           'sortBy=popularity&'
           'apiKey=0e24ed7870d04cc392d0a5804381faf7')
    
    response = requests.get(url)
    
    result = response.json()
    
    print(result)
    

    This should return the expected response.