Skip to content
BeginnerPythonAPI Integrations

Fetch Data from a REST API with Python (No Libraries Needed)

Use Python’s standard library to request JSON from a public API and print the fields you need.

15 min3 stepsPublished

Python logo
Photo: Python Software Foundation / Wikimedia Commons

Prerequisites

  • Python 3.10 or newer installed
  • A terminal
  1. 1

    Understand the request

    A REST API returns data at a URL, usually as JSON. GitHub’s public API returns information about any public repository without a key (with a low rate limit).

  2. 2

    Write the script

    Create a file named repo_info.py:

    repo_info.py Tested
    import json
    import urllib.request
    
    URL = "https://api.github.com/repos/python/cpython"
    
    request = urllib.request.Request(URL, headers={"User-Agent": "virtuvia-tutorial"})
    with urllib.request.urlopen(request, timeout=10) as response:
        data = json.load(response)
    
    print(f"Repository: {data['full_name']}")
    print(f"Description: {data['description']}")
    print(f"Default branch: {data['default_branch']}")
  3. 3

    Run it

    terminal
    python repo_info.py
    output
    Repository: python/cpython
    Description: The Python programming language
    Default branch: main

Troubleshooting

HTTP Error 403: rate limit exceeded

Unauthenticated requests are limited per hour. Wait, or use an access token as described in GitHub’s documentation.

urllib.error.URLError

Check your internet connection or proxy settings.

Check your understanding

What does `json.load(response)` return here?