Search Unity

How to send API requests?

Discussion in 'Scripting' started by ksc_3899, Jul 16, 2019.

  1. ksc_3899

    ksc_3899

    Joined:
    Jan 1, 2019
    Posts:
    30
    I wish to get a JSON as a response for a API request. How do I send a API request and how to do the authorisation for the API request?
     
  2. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
  3. ksc_3899

    ksc_3899

    Joined:
    Jan 1, 2019
    Posts:
    30
    How do I take a JSON from a server with an API request? That JSON will be update daily and I wish to get that same JSON. However if we are hosting it, the URL will be changing for each JSON. So I want to get that as an API response from a server. For that I need to do authentication and how do I implement that?
     
  4. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
    Usually, if you are using an API that needs authentication, the first thing you do in a session is log in, using some public API request. That request, if you are successful, will then pass you an authentication token that you will pass back to the API whenever you make another request. How you store that token is up to you; you could use a static variable somewhere, or you could store it in PlayerPrefs, for example.
     
  5. ksc_3899

    ksc_3899

    Joined:
    Jan 1, 2019
    Posts:
    30
    I might be sounding really dumb, I am very much new to these networking stuff.

    What do you mean by a 'public API request'? And considering I have succefully stored the authentication token, how do I pass it back to the API when needed?
     
  6. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
    Any API that uses authentication of any kind must have some way for you to authenticate before you actually have a token. Often, that's going to involve you sending a request to a Login script, which doesn't require a token. Every other script on the server would then require an auth token to work. So, in this context, 'public' means 'doesn't require an auth token', while 'private' means 'requires a valid auth token'.
    Now, the way you pass it back to the API depends on the API. They will define how they expect the token. Some APIs will require the token to be placed in a header for the request, others will take it as an additional parameter to the script, and yet others will expect it as an element of the JSON payload. So the first thing you'll need to do is find out how the API wants to get the auth token, and then figure out how to do what the API is asking.
     
  7. ksc_3899

    ksc_3899

    Joined:
    Jan 1, 2019
    Posts:
    30
    Thanks lot. This was very helpful and to the point.
     
  8. jdnichollsc

    jdnichollsc

    Joined:
    Sep 23, 2017
    Posts:
    9