Welcome to my blog!


January 18, 2018 15:22




Example with Github

curl https://api.github.com/users/caspyin

Includes HTTP-Header information in the output

curl --include https://api.github.com/users/caspyin


curl -H "Authorization: token OAUTH-TOKEN" https://api.github.com/gists/starred
curl -H "Authorization: token OAUTH-TOKEN" https://api.github.com/user
curl https://api.github.com/gists/starred?access_token=e72e16c7e42f292c6912e7710c838347ae178b4a
curl https://api.github.com/gists/starred?access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&token_type=bearer

Example PHP Request

# using HTTP Basic Authentication
$ curl -u TestClient:TestSecret https://api.mysite.com/token -d 'grant_type=client_credentials'

# using POST Body
$ curl https://api.mysite.com/token -d 'grant_type=client_credentials&client_id=TestClient&client_secret=TestSecret'

A successful token request will return a standard access token in JSON format:

Trying out OAuth2 via CURL

During development, it happens that you quickly want to try out a RESTful request. If you are running this request against an OAuth2 protected resource, you’ll need an access_token. So what is the easiest approach to get one? Unfortunately, OAuth2 is not supported just like Basic Authentication in the browser. The easiest option I’ve found is using CURL, the command-line utility for HTTP requests.

To get an access token for user demo and password 1234, I simply use the OAuth2 Resource Owner Password flow. Keep in mind, the token endpoint would need to be HTTPS in production, but for development this is fine:

The responsen will be the usual one:

Next, if you want to access a protected resource you have to pass the Authorization header. Let’s access our “current user” resource:

And the Response will be similar to this:

I hope you find this pretty straightforward, too!


REST API, JSON, Token and OAuth2



REST API bao gồm các thành phần sau:

  • Điểm cuối (endpoint)
  • Phương pháp (method)
  • Tiêu đề (header)
  • Dữ liệu (data)

REST API bao gồm 5 method cơ bản sau:

  • GET
  • POST
  • PUT

REST API trả về các trạng thái HTTP Status Code như sau

  • 200+ nghĩa là yêu cầu đã thành công .
  • 300+ nghĩa là yêu cầu được chuyển hướng đến một URL khác
  • 400+ có nghĩa là một lỗi bắt nguồn từ khách hàng đã xảy ra
  • 500+ nghĩa là lỗi xuất phát từ máy chủ đã xảy ra

Để gửi dữ liệu qua cURL

curl -X POST <URL> -d property1=value1

Để gửi nhiều trường dữ liệu:

curl -X POST <URL> -d property1=value1 -d property2=value2

Để gửi dữ liệu qua cURL

curl -X POST https://requestb.in/1ix963n1 \ -H "Content-Type: application/json" \ -d '{ "property1":"value1", "property2":"value2" }'

Để xác thực bằng tên đăng nhập và mật khẩu

curl -x POST -u "username:password" https://api.github.com/user/repos


Recent posts