REST API with cURL draft

Last modified 5 days ago / Edit on Github
draft
This is a draft, the content is not complete and of poor quality!
  • Official doc.
  • In Postman, we can click on "Code snippet" icon (on the right side) to show the curl command (and other commands too).

General

Note that, -X = --request.

curl -X [method] [options] [URL]

request in Python

👉 Official documentation.

import requests
# GET
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get('https://api.github.com/events', headers=headers)
# POST
r = requests.post('https://httpbin.org/post', data={'key': 'value'})
# For JSON-encoded
import json
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload))

Parameters in URL,

payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get('https://httpbin.org/get', params=payload)
print(r.url) # https://httpbin.org/get?key1=value1&key2=value2&key2=value3

Response

r.text
# '[{"repository":{"open_issues":0,"url":"https://github.com/...
# Binary Response Content
r.content
# b'[{"repository":{"open_issues":0,"url":"https://github.com/...
# JSON Response Content
r.json()
# [{'repository': {'open_issues': 0, 'url': 'https://github.com/...

Status code?

r.status_code # 200

r.status_code == requests.codes.ok # True

Headers?

r.headers

If response contains cookies?

r.cookies

Some examples

GET

curl -X GET 'http://abc:3000/xyz/enpoint?paramOne=1&paramTwo=2' \
--header 'clientEmail: [email protected]' \
--header 'privateKey: LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JSUV2Z0lCQU'
}'

POST

The JSON data must be in form of '{with the "double quotes" inside}'. This "{single 'quote' inside}" will not work!

In case you wanna get a good form of data (with the quotes) from a variable (Python),

import json
data = "{'x': 1, 'y': 2}"
data = json.dumps(data)
# data will be:
# '{"x": 1, "y": 2}'
curl -X POST 'http://abc:3000/xyz/enpoint?paramOne=1&paramTwo=2' \
--header 'clientEmail: [email protected]' \
--header 'privateKey: LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JSUV2Z0lCQU' \
--header 'Content-Type: application/json' \
--data-raw '{
"dataMain": {
"keyOne": "valueOne",
"keyTwo": 2
}
}'

or,

curl -X POST -H "Content-Type: application/json" \
-d '{"name": "linuxize", "email": "[email protected]"}' \
https://example/contact

Or with a JSON file,

curl -X POST \
-H "Content-Type: application/json" \
--data @.folder/file.json \
http://localhost:8080/ui/webapp/conf

With a form

<form method="POST" enctype='multipart/form-data' action="upload.cgi">
<input type=file name=upload>
<input type=submit name=press value="OK">
</form>

<!-- POST with file upload
-F = --form
-->
curl -F [email protected]/home/user/Pictures/wallpaper.jpg -F press=OK [URL]
Support Thi Support Thi