Will
Will

Reputation: 2410

PowerShell Invoke-WebRequest | API Call

I'm using Gitea and I try to create a user using an API call in PowerShell:

Testing Plateforme : https://try.gitea.io/

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

API Token : 3bb81a498393f4af3d278164b5755fc23b74b785

Username : Will-stackoverflow

Password : willwill

Here it's what I have tried so far :

# Filling my var with some data
$username="myuser"
$email="[email protected]"
$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

My $JSON var is fed properly :

{
    "Password":  "P@w0rd",
    "full_name":  "My User",
    "Username":  "myuser",
    "Email":  "[email protected]",
    "source_id":  0,
    "login_name":  "myuser",
    "send_notify":  "false"
}

But there is the result (from my prod environement as I can't get it to work at all using the online plateforme) :

enter image description here

To me it sounds like the fields "Username", "Email" and "Password" are required, but they are filled in my displayed JSON. What am I missing or doing wrong ?

EDIT :

Adding the -ContentType 'application/json' parameter to the Invoke-WebRequest command as suggested by Theo :

enter image description here

Upvotes: 3

Views: 3164

Answers (1)

Theo
Theo

Reputation: 61218

Looking at the Swagger UI site, it seems to me the json must contain properties in lower-caps only

{
  "email": "[email protected]",
  "full_name": "My User",
  "login_name": "myuser",
  "password": "P@w0rd",
  "send_notify": $true,
  "source_id": 0,
  "username": "myuser"
}

Also, according to the Swagger site, you need to state the -ContentType. Your code would look like this:

# Filling my var with some data
$username="myuser"
$email="[email protected]"
$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'

Upvotes: 2

Related Questions