Search 

REST API with cURL

Nam Hoai Nguyen
Nam Hoai Nguyen
  • 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]

cURL in PHP

💡
We need to install the PHP extension “php-curl” to use it. Check Official Documentation to learn more
1// create & initialize a curl session
2$curl = curl_init();
3
4/**
5* Some code
6**/ 
7
8// close curl resource to free up system resources
9// (deletes the variable made by curl_init)
10curl_close($curl);
1# GET
2curl_setopt($curl, CURLOPT_URL, 'https://api.github.com/events');
3# request header
4curl_setopt($curl, CURLOPT_HTTPHEADER, array(
5    'Content-Type: application/json',
6		'User-Agent: cURL'
7 ));
8$r = curl_exec($curl);
1# POST
2curl_setopt($curl, CURLOPT_URL, 'https://httpbin.org/post');
3curl_setopt($curl, CURLOPT_POST, 1);
4# request header
5curl_setopt($curl, CURLOPT_HTTPHEADER, array(
6    'Content-Type: application/json',
7 ));
8curl_setopt($curl, CURLOPT_POSTFIELDS, '{"key": "value"}');
9$r = curl_exec($curl);

Response

1// Raw text
2$r
3
4# JSON
5json_decode($r, true);
Status code ???
1$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); // $statusCode = 200

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 the 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),
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>
1<!-- POST with file upload
2-F = --form
3-->
4curl -F upload=@/home/user/Pictures/wallpaper.jpg -F press=OK [URL]