API quick-start

Prerequisites:

  • Basic terminal / command line skills
  • caddy and curl in your PATH

First start Caddy:

  1. caddy start

Caddy is currently running idle (with a blank configuration). Give it a simple config with curl:

  1. curl localhost:2019/load \
  2. -X POST \
  3. -H "Content-Type: application/json" \
  4. -d @- << EOF
  5. {
  6. "apps": {
  7. "http": {
  8. "servers": {
  9. "hello": {
  10. "listen": [":2015"],
  11. "routes": [
  12. {
  13. "handle": [{
  14. "handler": "static_response",
  15. "body": "Hello, world!"
  16. }]
  17. }
  18. ]
  19. }
  20. }
  21. }
  22. }
  23. }
  24. EOF

Giving a POST body with Heredoc can be tedious, so if you prefer to use files, save the JSON to a file called caddy.json and then use this command instead:

  1. curl localhost:2019/load \
  2. -X POST \
  3. -H "Content-Type: application/json" \
  4. -d @caddy.json

Now load localhost:2015 in your browser or use curl:

  1. curl localhost:2015
  2. Hello, world!

We can also define multiple sites on different interfaces with this JSON:

  1. {
  2. "apps": {
  3. "http": {
  4. "servers": {
  5. "hello": {
  6. "listen": [":2015"],
  7. "routes": [
  8. {
  9. "handle": [{
  10. "handler": "static_response",
  11. "body": "Hello, world!"
  12. }]
  13. }
  14. ]
  15. },
  16. "bye": {
  17. "listen": [":2016"],
  18. "routes": [
  19. {
  20. "handle": [{
  21. "handler": "static_response",
  22. "body": "Goodbye, world!"
  23. }]
  24. }
  25. ]
  26. }
  27. }
  28. }
  29. }
  30. }

Update your JSON then perform the API request again.

Try out your new “goodbye” endpoint in your browser or with curl to make sure it works:

  1. curl localhost:2016
  2. Goodbye, world!

When you are done with Caddy, make sure to stop it:

  1. caddy stop

There’s a lot more you can do with the API, including exporting configuration and making fine-grained changes to the config (as opposed to updating the whole thing). Be sure to read the full API tutorial to learn how!

Further reading