Some API endpoints require that the requester verifies that they are logged in as a specific user - that is, they require authorization. To pass authorization to an endpoint, specify your API Token in either the URL's query string ?x-token=<token>
or the X-Token
request header.
To actually get the API token used for authentication, make a request to https://scratch.mit.edu/session that matches this description:
- The method/URL is
GET https://scratch.mit.edu/session/
. - The
Cookie
header contains your session ID (scratchsessionsid={...}
). - The
X-Requested-With
header isXMLHttpRequest
.
This will respond with a fairly length JSON object of the following form:
{
user: {
id: 14792872
banned: false
username: "_nix"
token: "..."
thumbnailUrl: "//cdn2.scratch.mit.edu/get_image/user/14792872_32x32.png"
dateJoined: "2016-02-09T18:32:50"
email: "..."
}
permissions: {
admin: false
scratcher: true
new_scratcher: false
social: true
educator: false
educator_invitee: false
student: false
}
flags: {
must_reset_password: false
must_complete_registration: false
has_outstanding_email_confirmation: false
show_welcome: true
confirm_email_banner: true
unsupported_browser_banner: true
}
}
That's a pretty lengthy response, but it's self-explanatory. The API token you should use for authorization is stored in user.token
.
Of course, in order to fetch the session data (and thus API token) in the first place, you'll need to be logged into the Scratch website. To do that, make a request according to the following:
- The method/URL is
POST https://scratch.mit.edu/login/
. - The
Cookie
header specifies a CSRF token (scratchcsrftoken={...}
). - The
X-CSRFToken
header also specifies a CSRF token. - The
Referer
header ishttps://scratch.mit.edu
.
If you specified the correct password for that username, you'll get a response that looks something like this:
[
{
username: _nix
num_tries: 1
success: 1
msg: ""
messages: []
id: 14792872
}
]
Do note that the {...success: 1...}
object is itself contained in an array - you'll want to do something like response[0].success
to check if the login succeeded.
If you didn't specify the correct password or username, you'll get success: 0
instead, and an error message will be specified on msg
. (This is translated according to the scratchlanguage
cookie.)
If you've failed to specify the right password so many times that Scratch requires you solve a CAPTCHA before trying again, there will be a redirect: "/login_retry/"
property.
Some Scratch endpoints and services require that you pass a CSRF token (especially ones that are on domains other than api.scratch.mit.edu
). This token can be fetched from the Scratch website by simply making a GET
request to https://scratch.mit.edu/csrf\_token/, which will set the cookie scratchcsrftoken
. Typically passing this cookie to endpoints that require a CSRF token will be enough to work (setting the X-CSRFToken
header also works).