DEV Community

Max
Max

Posted on

1 1

Read and Write JSON in Python Requests from API

Python requests module allows you to send HTTP requests, The response from the HTTP request will have content, status, header meta details.

Using the requests package we can make a get request to a API which will return a JSON response it will be parse as python dictionary data.

getData function is used to make api call and parse data, we can check the response status by checking the status_code from response. And function writeData is used to write the response as json to local storage.

import json
import requests

def getData():
    url = "https://dummyjson.com/products/1"
    r = requests.get(url)
    print("Status:", r.status_code)

    return r.json()


def writeData(data):
    with open("jsonfile.json", "w") as file:
        json.dump(data, file, indent=4)


data = getData()

writeData(data)
Enter fullscreen mode Exit fullscreen mode

python requests get method data from response

Explore Other Related Articles

Read and Write Python Json
How to combine two dictionaries in python using different methods
How to check if a key exists in a dictionary python
Python try exception tutorial
Python classes and objects tutorial
Python Recursion Function Tutorial

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more