Home > OS >  how to get a specific objects in an API?
how to get a specific objects in an API?

Time:11-18

Hi i'm trying to consume an API in python, I made the connection and it works pretty well. In that API I have 100 results, and I just want to get 10 of them, do you know how to do that?

import requests
import pprint

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


pprint.pprint(response.json())

I tried with list comprehensions but I don't get how to use them in the dictionary for that API

CodePudding user response:

When you make your request, if it was valid, the response object has a json method which returns the json data of your response. In your case response.json() gives you a list of json objects. You can manipulate that like any python list.

result = response.json()
first_ten = result[:10]

What the [:10] notation means is "Give me a piece of the list starting from zero up to 10". The zero is implied because no first number is specified - it's the same as result[0:10] and you can use this notation to get any subsequence of the list you want.

P.S. Your url value is missing an s - 'https://jsonplaceholder.typicode.com/post', the right url is - 'https://jsonplaceholder.typicode.com/posts'

  • Related