http_request_class.rst 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. .. _doc_http_request_class:
  2. Making HTTP requests
  3. ====================
  4. The :ref:`HTTPRequest <class_HTTPRequest>` node is the easiest way to make HTTP requests in Godot.
  5. It is backed by the more low-level :ref:`HTTPClient <class_HTTPClient>`, for which a tutorial is available :ref:`here <doc_http_client_class>`.
  6. For the sake of this example, we will create a simple UI with a button, that when pressed will start the HTTP request to the specified URL.
  7. Preparing scene
  8. ---------------
  9. Create a new empty scene, add a CanvasLayer as the root node and add an script to it. Then add two child nodes to it: a Button and an HTTPRequest node. You will need to connect the following signals to the CanvasLayer script:
  10. - Button.pressed: When the button is pressed, we will start the request.
  11. - HTTPRequest.request_completed: When the request is completed, we will get the requested data as an argument.
  12. .. image:: img/rest_api_scene.png
  13. Scripting
  14. ---------
  15. Below is all the code we need to make it work. The URL points to an online API mocker; it returns a pre-defined JSON string, which we will then parse to get access to the data.
  16. ::
  17. extends CanvasLayer
  18. func _ready():
  19. pass
  20. func _on_Button_pressed():
  21. $HTTPRequest.request("http://www.mocky.io/v2/5185415ba171ea3a00704eed")
  22. func _on_HTTPRequest_request_completed( result, response_code, headers, body ):
  23. var json = JSON.parse(body.get_string_from_utf8())
  24. print(json.result)
  25. With this, you should see ``(hello:world)`` printed on the console; hello being a key, and world being a value, both of them strings.
  26. For more information on parsing JSON, see the class references for :ref:`JSON <class_JSON>` and :ref:`JSONParseResult <class_JSONParseResult>`.
  27. Note that you may want to check whether the ``result`` equals ``RESULT_SUCCESS`` and whether a JSON parsing error occurred, see the JSON class reference and :ref:`HTTPRequest <class_HTTPRequest>` for more.