📜  HTTPoison post json - Elixir (1)

📅  最后修改于: 2023-12-03 15:01:20.334000             🧑  作者: Mango

HTTPoison Post JSON - Elixir

HTTPoison is an HTTP client library for Elixir. It provides a simple and easy-to-use interface for making HTTP requests and consuming APIs. In this tutorial, we will focus on how to use HTTPoison to post JSON data to a server.

Installation

To use HTTPoison, we need to add it as a dependency in our mix.exs file:

def deps do
  [
    {:httpoison, "~> 1.7"}
  ]
end

After adding the dependency, we can run mix deps.get to install it.

Making a POST request with JSON body

To make a POST request with a JSON body, we can use the HTTPoison.post/3 function. Here is an example:

require HTTPoison

# Construct the JSON payload
payload = %{name: "John", age: 30}

# Make the POST request
response = HTTPoison.post("http://example.com/api/users",
                          Poison.encode!(payload),
                          [{"Content-Type", "application/json"}])

In the example above, we first construct the JSON payload using a Map. We then use the Poison.encode!/1 function to convert the Map to a JSON string.

Next, we pass the URL, JSON payload, and HTTP headers to the HTTPoison.post/3 function. The headers specify that we are sending JSON data.

Finally, we capture the HTTP response in the response variable.

Handling the response

The response variable contains information about the HTTP response. We can check the status code and body of the response by inspecting the response.status_code and response.body fields, respectively.

Here is an example of how to handle the response:

case response do
  {:ok, %{status_code: 200, body: body}} ->
    IO.puts("Success!")
    IO.inspect(body)

  {:ok, %{status_code: code, body: body}} ->
    IO.puts("Error! Status code: #{code}")
    IO.inspect(body)

  {:error, %{reason: reason}} ->
    IO.puts("Request failed: #{reason}")
end

In the example above, we pattern match on the response variable to check for possible outcomes. If the request was successful, we print "Success!" and inspect the response body. If there was an error, we print "Error!" and the HTTP status code. If the request failed, we print the reason for the failure.

Conclusion

In this tutorial, we learned how to use HTTPoison to make a POST request with a JSON body. We also learned how to handle the HTTP response. HTTPoison is a powerful library for interacting with APIs in Elixir.