0
0
PythonHow-ToBeginner · 3 min read

How to Call REST API in Python: Simple Guide with Examples

To call a REST API in Python, use the requests library to send HTTP methods like GET or POST. Import requests, then use requests.get(url) or requests.post(url, data) to interact with the API and get the response.
📐

Syntax

The basic syntax to call a REST API in Python uses the requests library. You import it, then use methods like get(), post(), put(), or delete() with the API URL.

  • requests.get(url): Sends a GET request to fetch data.
  • requests.post(url, data): Sends data to the API.
  • response.status_code: Checks if the request was successful.
  • response.json(): Parses the response as JSON.
python
import requests

response = requests.get('https://api.example.com/data')
if response.status_code == 200:
    data = response.json()
    print(data)
💻

Example

This example shows how to call a public REST API to get JSON data and print it. It demonstrates sending a GET request and handling the response.

python
import requests

url = 'https://jsonplaceholder.typicode.com/posts/1'
response = requests.get(url)

if response.status_code == 200:
    post = response.json()
    print('Title:', post['title'])
    print('Body:', post['body'])
else:
    print('Failed to retrieve data, status code:', response.status_code)
Output
Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit Body: quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto
⚠️

Common Pitfalls

Common mistakes when calling REST APIs in Python include:

  • Not checking response.status_code before using the data.
  • Forgetting to import the requests library.
  • Not handling exceptions like connection errors.
  • Sending data in the wrong format (e.g., not using JSON when required).

Always check the API documentation for required headers and data format.

python
import requests

# Wrong way: Not checking status code
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
data = response.json()  # May fail if response is not 200
print(data)

# Right way: Check status code and handle errors
try:
    response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
    response.raise_for_status()  # Raises error for bad status
    data = response.json()
    print(data)
except requests.exceptions.RequestException as e:
    print('Error:', e)
📊

Quick Reference

Here is a quick summary of common requests methods and usage tips:

MethodDescriptionExample
requests.get(url)Fetch data from APIrequests.get('https://api.example.com')
requests.post(url, json=data)Send JSON data to APIrequests.post('https://api.example.com', json={'key':'value'})
response.status_codeCheck HTTP status codeif response.status_code == 200:
response.json()Parse JSON responsedata = response.json()
response.textGet raw response textprint(response.text)

Key Takeaways

Use the requests library to easily call REST APIs in Python.
Always check response.status_code before using the response data.
Use response.json() to parse JSON responses from APIs.
Handle exceptions to avoid crashes on network errors.
Refer to API docs for required headers and data formats.