PowerShell Invoke-WebRequest | API调用

时间:2018-07-24 14:41:22

标签: json api powershell httpwebrequest

我使用的是Gitea,我尝试使用PowerShell中的API调用来创建用户:

  

测试平台:https://try.gitea.io/

     

API URL:https://try.gitea.io/api/swagger

     

API令牌:3bb81a498393f4af3d278164b5755fc23b74b785

     

用户名:Will-stackoverflow

     

密码:遗嘱

这是到目前为止我尝试过的:

# Filling my var with some data
$username="myuser"
$email="myuser@mydomain.com"
$full_name="My User"
$password="P@$$w0rd"

# Building a hash with my data
$hash = @{
     Email = $($email);
     full_name = $($full_name);
     login_name = $($username);
     Password = $($password);
     send_notify = "false";
     source_id = 0;
     Username = $($username)
}

# Converting my hash to json format
$JSON = $hash | convertto-json
# Displaying my JSON var
$JSON

Invoke-WebRequest -uri "http://try.gitea.io/api/v1/admin/users?access_token=3bb81a498393f4af3d278164b5755fc23b74b785" -Method POST -Body $JSON

我的$JSON变量输入正确:

{
    "Password":  "P@w0rd",
    "full_name":  "My User",
    "Username":  "myuser",
    "Email":  "myuser@mydomain.com",
    "source_id":  0,
    "login_name":  "myuser",
    "send_notify":  "false"
}

但是有结果(来自我的产品环境,因为我无法使用在线平台完全使它起作用)

enter image description here

对我来说,听起来"Username""Email""Password"字段是必填字段,但是它们填充在我显示的JSON中。我想念什么或做错什么了?

编辑:

根据Theo的建议,将-ContentType 'application/json'参数添加到Invoke-WebRequest命令中:

enter image description here

1 个答案:

答案 0 :(得分:1)

Swagger UI网站上,我觉得json必须只包含小写字母的属性

{
  "email": "myuser@mydomain.com",
  "full_name": "My User",
  "login_name": "myuser",
  "password": "P@w0rd",
  "send_notify": $true,
  "source_id": 0,
  "username": "myuser"
}

此外,根据Swagger网站,您需要声明 -ContentType 。 您的代码如下所示:

# Filling my var with some data
$username="myuser"
$email="myuser@mydomain.com"
$full_name="My User"
$password="P@$$w0rd"

# Building a hash with my data
$hash = @{
     email = $($email);          # string
     full_name = $($full_name);  # string
     login_name = $($username);  # string
     password = $($password);    # string
     send_notify = $false;       # boolean
     source_id = 0;              # int
     username = $($username)     # string
}



# Converting my hash to json format
$JSON = $hash | ConvertTo-Json
# Displaying my JSON var
$JSON

# just to make it somewhat easier on the eyes
$token = "3bb81a498393f4af3d278164b5755fc23b74b785"
$url = "http://try.gitea.io/api/v1/admin/users?access_token=$token"

Invoke-WebRequest -uri $url -Method POST -Body $JSON -ContentType 'application/json'