DEV Community

Cover image for How we can fetch api using requests in python
Mert
Mert

Posted on

How we can fetch api using requests in python

Introduction

An API, or Application Programming Interface, is a server that you can use to retrieve and send data to using code. APIs are most commonly used to retrieve data, and that will be the focus of this beginner tutorial.

starting by prepare venv:

in the terminal

python3 -m venv venv
source venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

then we need to install requests

in the terminal

pip3 install requests
Enter fullscreen mode Exit fullscreen mode

Make our first request

after creating app.py file

import requests
url ='https://animechan.vercel.app/api/random'
response = requests.get(url=url)
print(response.status_code)   # must be 200
Enter fullscreen mode Exit fullscreen mode
  • 200: Everything went okay, and the result has been returned (if any).
  • 301: The server is redirecting you to a different endpoint. This can happen when a company switches domain names, or an endpoint name is changed.
  • 400: The server thinks you made a bad request. This can happen when you don’t send along the right data, among other things.
  • 401: The server thinks you’re not authenticated. Many APIs require login credentials, so this happens when you don’t send the right credentials to access an API.
  • 403: The resource you’re trying to access is forbidden: you don’t have the right permissions to see it.
  • 404: The resource you tried to access wasn’t found on the server.
  • 503: The server is not ready to handle the request.

after we get checked our request we can start getting response results

import json.py
...
with open('response.json','w') as f :
    if (response.status_code == 200):
        json.dump(response.json(),f)
Enter fullscreen mode Exit fullscreen mode

resources:
https://www.dataquest.io/blog/python-api-tutorial/

used api :
https://animechan.vercel.app/

Top comments (0)