0

I am practicing making requests to APIs with Python. I am currently practicing with this API found on GitHub: https://github.com/vdespa/introduction-to-postman-course/blob/main/simple-books-api.md.

I would like to make a POST request to order a book. To make this request I provide an int book ID and a str customer name. However, the response I am getting is consistently "Invalid or missing bookId".

But when I use Postman to make this same request it works, responding with a True boolean and a str order ID. It also works when I use cURL and my terminal.

Any help would be appreciated! Thank you. :)

import requests
import json

order_url = "https://simple-books-api.glitch.me/orders"

my_post_1 = {"bookId" : 1, 
             "customerName" : "Anna"}

header_1 = {"Authorization" : my_token}

post_text_1 = requests.post (order_url, data = my_post_1, headers = header_1)
print ("status:", post_text_1)
print ("respose:", post_text_1.text)
finn
  • 1
  • 2

1 Answers1

0

When a request works in Postman and/or the browser but not in requests, check the headers. This is usually the cause of the problem. Make the headers the same and then try, or just try adding the more commonly required headers. In this case, the Content-Type header seems to be needed. And you should dump the data to a json string or try what Buran suggests in the comments. The following worked for me:

import requests
import json

my_token = "8e7d3ea30584c70a71be507a2ba8250bee25126152667616d27d4a2e4d186ea3"

order_url = "https://simple-books-api.glitch.me/orders"

my_post_1 = {"bookId":1,
             "customerName":"Anna"}

header_1 = {
        "Authorization" : my_token,
        "Content-Type": "application/json"
        }

post_text_1 = requests.post (order_url, data = json.dumps(my_post_1), headers = header_1)                                                                                        
print ("status:", post_text_1)
print ("respose:", post_text_1.text)
Neil
  • 3,020
  • 4
  • 25
  • 48
  • That is what `json` instead of `data` would do conveniently for you. – buran Jun 07 '22 at 13:30
  • @buran does json add the header automatically? – Neil Jun 07 '22 at 13:30
  • 1
    yes, it does - https://stackoverflow.com/q/26685248/4046632 – buran Jun 07 '22 at 13:31
  • Also, the docs - https://requests.readthedocs.io/en/latest/user/quickstart/#more-complicated-post-requests check at the bottom of this section – buran Jun 07 '22 at 13:33
  • @buran post an answer. Yours should be accepted. Mine works but is suboptimal. – Neil Jun 07 '22 at 13:34
  • Although I think my general point about checking headers is a good one. Helps you debug these problems in other cases. So I'm keeping my answer, though I don't think it should be the accepted one. – Neil Jun 07 '22 at 13:35
  • 1
    It's more or less a duplicate - I was looking for a good reference – buran Jun 07 '22 at 13:36