小白问题,为啥是红色的呀?

My goal now is to request the content in the example. How should I write the request format?

Bernhard via Daml Developers Community <daml@discoursemail.com> 于2021年12月15日周三 18:12写道:

@yuan_yan
I see a number of problems with your sample code.

  1. The second positional argument of the post method of the requests library is “data”, not “headers”. It represents the body of the HTTP request. So, the headers that you provide in the variable named “header” are passed as the body of the HTTP request, not as the headers. This is why the request comes back with HTTP status 401, as it is missing the Authorization header. To avoid this kind of problem I recommend using kwargs rather than positional arguments, e.g. requests.post(url=url, data=data, headers=headers).
  2. You need to provide the body of the request, which contains the data you want to pass to the Daml action. E.g. to create of a Coin contract you need to provide issuer, owner, amount and delegates in the request body. See Create a new Contract section in HTTP JSON API Service documentation.
  3. The headers in your request are malformed. The information required to authorize your request (such as ledger and party represented by ledgerId and actAs parameters) is encoded in JWT. You have to provide this information when you obtain the token. But you don’t have to explicitly include it in the headers of your HTTP request. HTTP JSON API Service parses the authorization parameters out of JWT. In other words it does not look at any headers other than Authorization. Adding ledgerId and actAs headers to your request has no effect. Including these headers in your request will not make the request fail. But it shows that you don’t yet have a good grasp of how the authorization is performed. I suggest you read the section titled Party-specific Access Tokens in HTTP JSON API Service documentation.

Here’s a complete code sample for you. Note that the value of templateId parameter in the HTTP request body must be provided as “<package ID>:<module>:<entity>” or as “<module>:<entity>”. In my example below the value of templateId is “Main:Coin”, where Main is the name of the Daml module and Coin is the name of the template.

import requests
url = "http://localhost:7575/v1/create"
headers = {"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwczovL2RhbWwuY29tL2xlZGdlci1hcGkiOnsibGVkZ2VySWQiOiJNeUxlZGdlciIsImFwcGxpY2F0aW9uSWQiOiJIVFRQLUpTT04tQVBJLUdhdGV3YXkiLCJhY3RBcyI6WyJBbGljZSJdfX0.34zzF_fbWv7p60r5s1kKzwndvGdsJDX-W4Xhm4oVdpk"}
data = '{"templateId": "Main:Coin", "payload": {"issuer": "Alice","owner": "Alice","amount": "999.99","delegates": []}}'
res = requests.post(url, data=data, headers=headers)
print (res.status_code)
print (res.text)
2 Likes