Friday, September 4, 2020

Making REST API Requests in Python

 

What is a REST API?

An API allows two software programs to communicate with each other. One program can call another program’s API to get access to data or functionality of the other program.

REST API (Representational state transfer) is an API that uses HTTP requests for communication with web services.

Types of Requests

  1. GET: retrieve information.
  2. POST: adds new data to the server.
  3. PUT: changes existing information.
  4. DELETE: deletes existing information.

Status Codes

200 – OK. The request was successful.

204 – No Content. The server successfully processed the request and did not return any content.

301 – Moved Permanently. 

400 – Bad Request. 

401 – Unauthorized.

403 – Forbidden. Access to the specified resource is denied.

404 – Not Found. 

500 – Internal Server Error.

 

 

Making API Requests in Python

If you use conda the commands used are:

>>conda install requests

>> import requests

To make a ‘GET’ request, we’ll use the requests.get() function

Eg:

>>response = requests.get("http://api.open-notify.org/astros.json")

>>print(response.status_code)

>> print(response.json())

The json library has two main functions:

json.dumps() — Takes in a Python object, and converts (dumps) it to a string.

json.loads() — Takes a JSON string, and converts (loads) it to a Python object.

 

>>import json

 

def jprint(obj):

    # create a formatted string of the Python JSON object

    text = json.dumps(obj, sort_keys=True, indent=4)

    print(text)

 

jprint(response.json())

 

output:

{

    "message": "success",

    "number": 3,

    "people": [

        {

            "craft": "ISS",

            "name": "Chris Cassidy"

        },

        {

            "craft": "ISS",

            "name": "Anatoly Ivanishin"

        },

        {

            "craft": "ISS",

            "name": "Ivan Vagner"

        }

    ]

}

CREATE

To create resources in a REST environment, we most commonly use the HTTP POST method. POST creates a new resource of the specified resource type.

Code:

#import requests module

import requests

import json

# Making a get request

#task=("refresh_token":" ","access_token":" ","expires_in":"")

url = 'https://api.hubapi.com/oauth/v1/token?grant_type=refresh_token&client_id=283ad037-6427-47fe-b706-7b96e5d27cd6&client_secret=81193adc-8887-4ed4-a292-48f4a2659916&refresh_token=d14e6078-1cb4-4ed1-884c-38626646bd28'

header = {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}

response=requests.post(url=url,headers=header)

print(response.status_code)

Output:

200

READ

To read we use the HTTP GET method. GET returns a representation in XML or JSON and an HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST) 401 Unauthorized.

Code:

import requests

r=requests.get('http://demo.guru99.com')

print(r.status_code)

output:

                                                                                                                                            

1 comment:

  1. very nice information. Thanks you for you post bloggers or Totally inspirational.
    Visit this page

    ReplyDelete