Skip to main content

Request():post()

Execute a POST request and return a Response object. This method is used to send data to a server, typically to create a new resource.

Signature

post(): Response

Returns

Response - The response object containing the server response

Description

The post() method sends an HTTP POST request to the URL specified when creating the Request object. POST requests are typically used to submit data to a server for processing, such as creating new records, submitting forms, or uploading data.

Use setParameter() to add data to the request body before calling post().

Examples

Basic POST Request

-- Create a POST request with parameters
local response = Request("https://api.example.com/users")
:setParameter("name", "John Doe")
:setParameter("email", "john@example.com")
:post()

POST Request with JSON Headers

-- POST request with JSON content type
local response = Request("https://api.example.com/posts")
:setHeader("Content-Type", "application/json")
:setHeader("Authorization", "Bearer your-token-here")
:setParameter("title", "My New Post")
:setParameter("body", "This is the content of my post")
:setParameter("userId", "1")
:post()

Processing POST Response

-- Make the POST request and handle the response
local response = Request("https://api.example.com/comments")
:setHeader("Content-Type", "application/json")
:setParameter("postId", "1")
:setParameter("name", "Anonymous User")
:setParameter("email", "user@example.com")
:setParameter("body", "Great article!")
:post()

-- Get the response data
local data = response:getData()
local statusCode = response:getResponseCode()

if statusCode == 201 then
print("Comment created successfully!")
print("Response: " .. data)
else
print("Failed to create comment. Status: " .. statusCode)
end

Form Submission with POST

-- Simulate a form submission
local response = Request("https://example.com/login")
:setHeader("Content-Type", "application/x-www-form-urlencoded")
:setParameter("username", "myusername")
:setParameter("password", "mypassword")
:setParameter("remember", "true")
:post()

local loginResponse = response:getData()
local status = response:getResponseCode()

if status == 200 then
print("Login successful!")
else
print("Login failed. Status: " .. status)
end

Notes

  • Use setParameter() to add data to the request body before calling post()
  • POST requests can have a request body containing the data to be sent
  • The method returns a Response object which you can use to access the response data and status code
  • For successful resource creation, servers typically return a 201 status code
  • Always check the response status code to ensure the request was successful
  • POST requests are not idempotent - making the same request multiple times may create multiple resources