Wechat search [front-end full stack developer] pay attention to this hair loss, stall, selling goods, continuous learning programmer, the first time to read the latest article, will give priority to two days to publish new articles. Attention can be a gift package, you can save a lot of money!

In this tutorial, we introduce the basic cURL options and show you how to use them with examples. Then we develop a Node/Express server with three endpoints to demonstrate how to perform cURL’s GET/POST requests to the server using the cURL options described in this article.

There are many options to use with cURL, and here are the basic options you can use to quickly test API endpoints.

introduce

CURL is a transport tool for transferring data from and to a server. It supports a variety of Internet transport protocols including:

  • DICT
  • FILE
  • FTP, FTPS
  • GOPHER
  • HTTP, HTTPS
  • IMAP, IMAPS
  • LDAP, LDAPS
  • POP3, POP3S
  • RTMP, RTSP
  • SCP, SFTP
  • SMB, SMBS
  • SMTP, SMTPS
  • TELNET and TFTP

You can use cURL to perform useful tricks such as proxy support, user authentication, FTP uploaders, HTTP POST, SSL connections, cookies, file transfer recovery, Metalink, and more.

CURL is used on the command line to quickly test apis during software development. I personally use cURL when I want to test all my apis on a Node.js server. This is a very handy tool for developers.

Postman is cool, but cURL is cool. – Chidume Nnamdi

In this article, we’ll cover the basic cURL functions and options. You’ll also learn how to use cURL to perform GET and POST requests on API endpoints.

The cURL option

– request or – X

– Request and -x specify custom request methods that can be used to communicate with the HTTP server. The specified request method is used instead of other methods (default: GET).

To perform a POST request:

curl --request POST
Copy the code

To perform a GET request:

curl --request GET
Copy the code

–url</code

This specifies the URL from which we will fetch or transfer data, which is handy when you want to specify a URL in a configuration file.

If a given URL lacks a scheme name (for example, “http://&#8221” or “ftp://&#8221”), cURL will guess based on the host.

This protocol is used if the outermost subdomain matches DICT, FTP, IMAP, LDAP, POP3, or SMTP. Otherwise, HTTP is used.

For example, if you want to perform a GET request on localhost:3000 on your local server, set the — URL to localhost:3000:

curl --request GET \
    --url http://localhost:3000
Copy the code

To perform POST on the same URL:

curl --request POST \
    --url http://localhost:3000
Copy the code

Note: The backslash \ is used to separate options in cURL.

The same is true for external apis.

Suppose you want to get… from moviesdb.com/movies/all.

curl --request GET \
    --url https://moviesdb.com/movies/all
Copy the code

The list of all movies in MoviedB will be retrieved and printed.

— the header or -h

This option sets the header information for the request.

The extra header included in the request when sending HTTP to the server. You can specify any number of additional headers. Note that if you want to add a custom header with the same name as the header used inside curl, the header you set externally will be used instead of the internal header.

This mirrors what we do in normal programming, especially with XMLHttpRequest in JavaScript:

const xhttp = new XMLHttpRequest()

xhttp.setHeader("Content-Type", "application/json")
Copy the code

The header information is used to communicate the incoming or expected data type to the Web server, and the data type sent should be the same as that specified in the header.

We can use header files to obtain CORS permissions and even to obtain permissions for certain types of request methods. There are many things we can do with header files.

So in cURL, we can set the header with the -header option:

curl --request POST \
  --url http://localhost:5000/api/user \
  --header 'content-type: application/json'
Copy the code

Here, we are send a POST request to http://localhost:5000/api/user endpoint, and through – the header content-type: Application /json ‘tells the server that the data we are sending is a JSON data type.

— data or 3-d

This option is used to send data to the HTTP server, which is mainly used in POST requests because we are sending data to the server we are adding to the database. So in cURL, you can specify the data as POST by setting the -data option.

The specified data is sent to the HTTP server in a POST request, just as the browser does when the user fills out an HTML form and presses the submit button.

Here’s an example:

curl --request POST \ --url http://localhost:5000 \ --header 'content-type: Application /json' \ --data '{"name":"Arrow","description":"bad movie","rating":"7.0","image":"michaeljackson.png"}'Copy the code

Here, we are performing a POST request to the http://localhost:5000 endpoint.

We set the data to send to the server in the — data option, i.e. ‘{“name”:”Arrow”,”description”:”bad Movie “,”rating”:”7.0″,”image”:”michaeljackson.png “}

Use cURL in Node.js/express.js

Let’s see how to set up the Node.js/express.js server and test the endpoint with cURL:

// server.js

const express = require("express")
const cors = require('cors')
const bodyParser = require('body-parser')
const helmet = require('helmet')

const app = express()

let port = 5000 || process.env.PORT

/** Set up middleware */
app.use(cors())
app.use(bodyParser.json({limit: '50mb'}))
app.use(helmet())

let users = []
let currId  Date.now()

app.get("api/user/:id".(req, res, next) = > {
  const userId = req.params.id
  const users = users.filter(user= > user.id === userId)
  if(users.length > 0)
    res.send({ user: users[0]})else
    res.send({mesg: "No user found."})
  next()
})

app.get("api/users".(req, res, next) = > {
  res.send({ users })
  next()
})

app.post("api/user".(req, res, next) = > {
  let bdy = req.body
  bdy = { id: ++currId, ... bdy } users.push(bdy) res.send({user: bdy })
  next()    
})

/** Start the server */
app.listen(port, () = > {
  console.log(`Server started at port: ${port}`);
});
Copy the code

We have some small API endpoints here:

  • GEt api/users
  • GET api/user/:id
  • POST api/user

It extracts all users (specific users) by their IDS and can add new users.

Start the server:

node server.js

Server started at port: 5000
Copy the code

Now, a POST request to be executed on the API/user, we set – the url to http://localhost:5000/api/user, and set – the request to the POST, Set –header to Content-Type :application/json.

We want to add a user:

name: "Chidume",
age: 28
Copy the code

So the data will be ‘{“name”: “Chidume”, “age”: “28”}’

So the cURL command would be:

curl --request POST \
  --url http://localhost:5000/api/user \
  --header 'content-type: application/json' \
  --data '{"name": "Chidume", "age": "28"}'

{ id: 5122435464, name: "Chidume", age: 28 }
Copy the code

We see the result from the server: the user and his ID are added to the database.

Let’s add another user:

curl --request POST \
  --url http://localhost:5000/api/user \
  --header 'content-type: application/json' \
  --data '{"name": "Nnamdi", "age": "21"}'

{ id: 5122435465, name: "Nnamdi", age: 21 }
Copy the code

We added another user “Nnamdi” and we can see the server ID and its results.

Now, let’s query “Chidume” through API /user/:id. Here: ID will be ID 5122435464. So cURL would be:

curl --request GET \ --url http://localhost:5000/api/user/5122435464 { user: { id: 5122435464, name: "Chidume", age: 28}}Copy the code

The server returns user Chidume whose ID is 5122435464.

Now let’s query a user that doesn’t exist:

curl --request GET \
  --url http://localhost:5000/api/user/2000000000


{ mesg: "No user found." }
Copy the code

This is the result returned on the server when we encounter a non-existent user.

Now, let’s query all users:

curl --request GET \
  --url http://localhost:5000/api/users


{ users: [ { id: 5122435465, name: "Nnamdi", age: 21 }, { id: 5122435464, name: "Chidume", age: 28 } ] }
Copy the code

As you can see, all users in the server are returned.

The end of the

If you have any questions about this, or if I should add, correct or remove anything, please feel free to comment.


Original: blog.logrocket.com

Chidume Nnamdi Follow