REST API with cURL

Anh-Thi Dinh
  • 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.
1curl -X [method] [options] [URL]

request in Python

1import requests
1# GET
2headers = {'user-agent': 'my-app/0.0.1'}
3r = requests.get('<https://api.github.com/events>', headers=headers)
1# POST
2r = requests.post('<https://httpbin.org/post>', data={'key': 'value'})
1# For JSON-encoded
2import json
3payload = {'some': 'data'}
4r = requests.post(url, data=json.dumps(payload))
Parameters in URL,
1payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
2r = requests.get('<https://httpbin.org/get>', params=payload)
3print(r.url) # <https://httpbin.org/get?key1=value1&key2=value2&key2=value3>

Response

1r.text
2# '[{"repository":{"open_issues":0,"url":"<https://github.com/>...
1# Binary Response Content
2r.content
3# b'[{"repository":{"open_issues":0,"url":"<https://github.com/>..
1# JSON Response Content
2r.json()
3# [{'repository': {'open_issues': 0, 'url': '<https://github.com/>...
Status code?
1r.status_code # 200
2
3r.status_code == requests.codes.ok # True
Headers?
1r.header
If response contains cookies?
1r.cookies

Some examples

GET

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

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),
1import json
2data = "{'x': 1, 'y': 2}"
3data = json.dumps(data)
4# data will be:
5# '{"x": 1, "y": 2}'
1curl -X POST '<http://abc:3000/xyz/enpoint?paramOne=1&paramTwo=2>' \
2	--header 'clientEmail: [email protected]' \
3	--header 'privateKey: LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JSUV2Z0lCQU' \
4	--header 'Content-Type: application/json' \
5	--data-raw '{
6		"dataMain": {
7			"keyOne": "valueOne",
8			"keyTwo": 2
9		}
10	}'
or,
1curl -X POST -H "Content-Type: application/json" \
2    -d '{"name": "linuxize", "email": "[email protected]"}' \
3    <https://example/contact>
Or with a JSON file,
1curl -X POST \
2  -H "Content-Type: application/json" \
3  --data @.folder/file.json \
4  <http://localhost:8080/ui/webapp/conf>

With a form

1<form method="POST" enctype='multipart/form-data' action="upload.cgi">
2  <input type=file name=upload>
3  <input type=submit name=press value="OK">
4</form>
5
6<!-- POST with file upload
7-F = --form
8-->
9curl -F upload=@/home/user/Pictures/wallpaper.jpg -F press=OK [URL]
Loading comments...