One place for hosting & domains

      How To Use Wget to Download Files and Interact with REST APIs


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Wget is a networking command-line tool that lets you download files and interact with REST APIs. It supports the HTTP,HTTPS, FTP, and FTPS internet protocols. Wget can deal with unstable and slow network connections. In the event of a download failure, Wget keeps trying until the entire file has been retrieved. Wget also lets you resume a file download that was interrupted without starting from scratch.

      You can also use Wget to interact with REST APIs without having to install any additional external programs. You can make GET, POST, PUT, and DELETE HTTP requests with single and multiple headers right in the terminal.

      In this tutorial, you will use Wget to download files, interact with REST API endpoints, and create and manage a Droplet in your DigitalOcean account.

      To follow along with this tutorial using a terminal in your browser, click the Launch an Interactive Terminal! button below:

      Launch an Interactive Terminal!

      Otherwise, if you’d like to use your local system or a remote server, open a terminal and run the commands there.

      Prerequisites

      To complete this tutorial, you will need:

      • Wget installed. Most Linux distributions have Wget installed by default. To check, type wget in your terminal and press ENTER. If it is not installed, it will display: command not found. You can install it by running the following command: sudo apt-get install wget.

      • A DigitalOcean account. If you do not have one, sign up for a new account.

      • A DigitalOcean Personal Access Token, which you can create via the DigitalOcean control panel. Instructions to do that can be found here: How to Generate a Personal Access Token.

      Downloading Files

      In this section, you will use Wget to customize your download experience. For example, you will learn to download a single file and multiple files, handle file downloads in unstable network conditions, and, in the case of a download interruption, resume a download.

      First, create a directory to save the files that you will download throughout this tutorial:

      • mkdir -p DigitalOcean-Wget-Tutorial/Downloads

      With the command above, you have created a directory named DigitalOcean-Wget-Tutorial, and inside of it, you created a subdirectory named Downloads. This directory and its subdirectory will be where you will store the files you download.

      Navigate to the DigitalOcean-Wget-Tutorial directory:

      • cd DigitalOcean-Wget-Tutorial

      You have successfully created the directory where you will store the files you download.

      Downloading a file

      In order to download a file using Wget, type wget followed by the URL of the file that you wish to download. Wget will download the file in the given URL and save it in the current directory.

      Let’s download a minified version of jQuery using the following command:

      • wget https://code.jquery.com/jquery-3.6.0.min.js

      Don’t worry if you don’t know what jQuery is – you could have downloaded any file available on the internet. All you need to know is that you successfully used Wget to download a file from the internet.

      The output will look similar to this:

      Output

      --2021-07-21 16:25:11-- https://code.jquery.com/jquery-3.6.0.min.js Resolving code.jquery.com (code.jquery.com)... 69.16.175.10, 69.16.175.42, 2001:4de0:ac18::1:a:1a, ... Connecting to code.jquery.com (code.jquery.com)|69.16.175.10|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 89501 (87K) [application/javascript] Saving to: ‘jquery-3.6.0.min.js’ jquery-3.6.0.min.js 100%[===================>] 87.40K 114KB/s in 0.8s 2021-07-21 16:25:13 (114 KB/s) - ‘jquery-3.6.0.min.js’ saved [89501/89501]

      According to the output above, you have successfully downloaded and saved a file named jquery-3.6.0.min.js to your current directory.

      You can check the contents of the current directory using the following command:

      The output will look similar to this:

      Output

      Downloads jquery-3.6.0.min.js

      Specifying the filename for the downloaded file

      When downloading a file, Wget defaults to storing it using the name that the file has on the server. You can change that by using the -O option to specify a new name.

      Download the jQuery file you downloaded previously, but this time save it under a different name:

      • wget -O jquery.min.js https://code.jquery.com/jquery-3.6.0.min.js

      With the command above, you set the jQuery file to be saved as jquery.min.js instead of jquery-3.6.0.min.js

      The output will look similar to this:

      Output

      --2021-07-21 16:27:01-- https://code.jquery.com/jquery-3.6.0.min.js Resolving code.jquery.com (code.jquery.com)... 69.16.175.10, 69.16.175.42, 2001:4de0:ac18::1:a:2b, ... Connecting to code.jquery.com (code.jquery.com)|69.16.175.10|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 89501 (87K) [application/javascript] Saving to: ‘jquery.min.js’ jquery.min.js 100%[==================================>] 87.40K 194KB/s in 0.4s 2021-07-21 16:27:03 (194 KB/s) - ‘jquery.min.js’ saved [89501/89501]

      According to the output above, you have successfully downloaded the jQuery file and saved it as jquery.min.js.

      You can use the ls command to list the contents of your current directory, and you will see the jquery.min.js file there:

      The output will look similar to this:

      Output

      Downloads jquery-3.6.0.min.js jquery.min.js

      So far, you have used wget to download files to the current directory. Next, you will download to a specific directory.

      Downloading a file to a specific directory

      When downloading a file, Wget stores it in the current directory by default. You can change that by using the -P option to specify the name of the directory where you want to save the file.

      Download the jQuery file you downloaded previously, but this time save it in the Downloads subdirectory.

      • wget -P Downloads/ https://code.jquery.com/jquery-3.6.0.min.js

      The output will look similar to this:

      Output

      --2021-07-21 16:28:50-- https://code.jquery.com/jquery-3.6.0.min.js Resolving code.jquery.com (code.jquery.com)... 69.16.175.42, 69.16.175.10, 2001:4de0:ac18::1:a:2b, ... Connecting to code.jquery.com (code.jquery.com)|69.16.175.42|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 89501 (87K) [application/javascript] Saving to: ‘Downloads/jquery-3.6.0.min.js’ jquery-3.6.0.min.js 100%[==================================>] 87.40K 43.6KB/s in 2.0s 2021-07-21 16:28:53 (43.6 KB/s) - ‘Downloads/jquery-3.6.0.min.js’ saved [89501/89501]

      Notice the last line where it says that the jquery-3.6.0.min.js file was saved in the Downloads directory.

      If you use the ls Downloads command to list the contents of the Downloads directory, you will see the jQuery file there:

      Run the ls command:

      The output will look similar to this:

      Output

      jquery-3.6.0.min.js

      Turning Wget’s output off

      By default, Wget outputs a lot of information to the terminal when you download a file. You can use the -q option to turn off all output.

      Download the jQuery file, but this time without showing any output:

      • wget -q https://code.jquery.com/jquery-3.6.0.min.js

      You won’t see any output, but if you use the ls command to list the contents of the current directory you will find a file named jquery-3.6.0.min.js.1:

      The output will look similar to this:

      Output

      Downloads jquery-3.6.0.min.js jquery-3.6.0.min.js.1 jquery.min.js

      Before saving a file, Wget checks whether the file exists in the desired directory. If it does, Wget adds a number to the end of the file. If you ran the command above one more time, Wget would create a file named jquery-3.6.0.min.js.2. This number increases every time you download a file to a directory that already has a file with the same name.

      You have successfully turned off Wget’s output, but now you can’t monitor the download progress. Let’s look at how to show the download progress bar.

      Showing the download progress bar

      Wget lets you show the download progress bar but hide any other output by using the -q option alongside the --show-progress option.

      Download the jQuery file, but this time only show the download progress bar:

      • wget -q --show-progress https://code.jquery.com/jquery-3.6.0.min.js

      The output will look similar to this:

      Output

      jquery-3.6.0.min.js.2 100%[================================================>] 87.40K 207KB/s in 0.4s

      Use the ls command to check the contents of the current directory and you will find the file you have just downloaded with the name jquery-3.6.0.min.js.2

      From this point forward you will be using the -q and --show-progress options in most of the subsequent Wget commands.

      So far you have only downloaded a single file. Next, you will download multiple files.

      Downloading multiple files

      In order to download multiples files using Wget, you need to create a .txt file and insert the URLs of the files you wish to download. After inserting the URLs inside the file, use the wget command with the -i option followed by the name of the .txt file containing the URLs.

      Create a file named images.txt:

      In images.txt, add the following URLs:

      images.txt

      https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313__340.jpg
      https://cdn.pixabay.com/photo/2016/01/05/17/51/maltese-1123016__340.jpg
      https://cdn.pixabay.com/photo/2020/06/30/22/34/dog-5357794__340.jpg
      

      The URLs link to three random images of dogs found on Pixabay. After you have added the URLs, save and close the file.

      Now you will use the -i option alongside the -P,-q and --show-progress options that you learned earlier to download all three images to the Downloads directory:

      • wget -i images.txt -P Downloads/ -q --show-progress

      The output will look similar to this:

      Output

      puppy-1903313__340.jp 100%[=========================>] 26.44K 93.0KB/s in 0.3s maltese-1123016__340. 100%[=========================>] 50.81K --.-KB/s in 0.06s dog-5357794__340.jpg 100%[=========================>] 30.59K --.-KB/s in 0.07s

      If you use the ls Downloads command to list the contents of the Downloads directory, you will find the names of the three images you have just downloaded:

      The output will look similar to this:

      Output

      dog-5357794__340.jpg jquery-3.6.0.min.js maltese-1123016__340.jpg puppy-1903313__340.jpg

      Limiting download speed

      So far, you have download files with the maximum available download speed. However, you might want to limit the download speed to preserve resources for other tasks. You can limit the download speed by using the --limit-rate option followed by the maximum speed allowed in kiloBits per second and the letter k.

      Download the first image in the images.txt file with a speed of 15 kB/S to the Downloads directory:

      • wget --limit-rate 15k -P Downloads/ -q --show-progress https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313__340.jpg

      The output will look similar to this:

      Output

      puppy-1903313__340.jpg.1 100%[====================================================>] 26.44K 16.1KB/s in 1.6s

      If you use the ls Downloads command to check the contents of the Downloads directory, you will see the file you have just downloaded with the name puppy-1903313__340.jpg.1.

      When downloading a file that already exists, Wget creates a new file instead of overwriting the existing file. Next, you will overwrite a downloaded file.

      Overwriting a downloaded file

      You can overwrite a file you have downloaded by using the -O option alongside the name of the file. In the code below, you will first download the second image listed in the images.txt file to the current directory and then you will overwrite it.

      First, download the second image to the current directory and set the name to image2.jpg:

      • wget -O image2.jpg -q --show-progress https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313__340.jpg

      The output will look similar to this::

      Output

      image2.jpg 100%[====================================================>] 26.44K --.-KB/s in 0.04s

      If you use the ls command to check the contents of the current directory, you will see the file you have just downloaded with the name image2.jpg.

      If you wish to overwrite this image2.jpg file, you can run the same command you ran earlier :

      • wget -O image2.jpg -q --show-progress https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313__340.jpg

      You can run the command above as many times as you like and Wget will download the file and overwrite the existing one. If you run the command above without the -O option, Wget will create a new file each time you run it.

      Resuming a download

      Thus far, you have successfully downloaded multiple files without interruption. However, if the download was interrupted, you can resume it by using the -c option.

      Run the following command to download a random image of a dog found on Pixabay. Note that in the command, you have set the maximum speed to 1 KB/S. Before the image finishes downloading, press Ctrl+C to cancel the download:

      • wget --limit-rate 1k -q --show-progress https://cdn.pixabay.com/photo/2018/03/07/19/51/grass-3206938__340.jpg

      To resume the download, pass the -c option. Note that this will only work if you run this command in the same directory as the incomplete file:

      • wget -c --limit-rate 1k -q --show-progress https://cdn.pixabay.com/photo/2018/03/07/19/51/grass-3206938__340.jpg

      Up until now, you have only downloaded files in the foreground. Next, you will download files in the background.

      Downloading in the background

      You can download files in the background by using the -b option.

      Run the command below to download a random image of a dog from Pixabay in the background:

      • wget -b https://cdn.pixabay.com/photo/2018/03/07/19/51/grass-3206938__340.jpg

      When you download files in the background, Wget creates a file named wget-log in the current directory and redirects all output to this file. If you wish to watch the status of the download, you can use the following command:

      The output will look similar to this:

      Output

      Resolving cdn.pixabay.com (cdn.pixabay.com)... 104.18.20.183, 104.18.21.183, 2606:4700::6812:14b7, ... Connecting to cdn.pixabay.com (cdn.pixabay.com)|104.18.20.183|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 33520 (33K) [image/jpeg] Saving to: ‘grass-3206938__340.jpg’ 0K .......... .......... .......... .. 100% 338K=0.1s 2021-07-20 23:49:52 (338 KB/s) - ‘grass-3206938__340.jpg’ saved [33520/33520]

      Setting a timeout

      Until this point, we have assumed that the server that you are trying to download files from is working properly. However, let’s assume that the server is not working properly. You can use Wget to first limit the amount of time that you wait for the server to respond and then limit the number of times that Wget tries to reach the server.

      If you wish to download a file but you are unsure if the server is working properly, you can set a timeout by using the -T option followed by the time in seconds.

      In the following command, you are setting the timeout to 5 seconds:

      • wget -T 5 -q --show-progress https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313__340.jpg

      Setting maximum number of tries

      You can also set how many times Wget attempts to download a file after being interrupted by passing the --tries option followed by the number of tries.

      By running the command below, you are limiting the number of tries to 3:

      • wget --tries=3 -q --show-progress https://cdn.pixabay.com/photo/2018/03/07/19/51/grass-3206938__340.jpg

      If you would like to try indefinitely you can pass inf alongside the --tries option:

      • wget --tries=inf -q --show-progress https://cdn.pixabay.com/photo/2018/03/07/19/51/grass-3206938__340.jpg

      In this section, you used Wget to download a single file and multiple files, resume downloads, and handle network issues. In the next section, you will learn to interact with REST API endpoints.

      Interacting with REST APIs

      In this section, you will use Wget to interact with REST APIs without having to install an external program. You will learn the syntax to send the most commonly used HTTP methods: GET, POST, PUT, and DELETE.

      We are going to use JSONPlaceholder as the mock REST API. JSONPlaceholder is a free online REST API that you can use for fake data. (The requests you send to it won’t affect any databases and the data won’t be saved.)

      Sending GET requests

      Wget lets you send GET requests by running a command that looks like the following:

      In the command above, the - after the -O option means standard output, so Wget will send the output of the URL to the terminal instead of sending it to a file as you did in the previous section. GET is the default HTTP method that Wget uses.

      Run the following command in the terminal window:

      • wget -O- https://jsonplaceholder.typicode.com/posts?_limit=2

      In the command above, you used wget to send a GET request to JSON Placeholder in order to retrieve two posts from the REST API.

      The output will look similar to this:

      Output

      --2021-07-21 16:52:51-- https://jsonplaceholder.typicode.com/posts?_limit=2 Resolving jsonplaceholder.typicode.com (jsonplaceholder.typicode.com)... 104.21.10.8, 172.67.189.217, 2606:4700:3032::6815:a08, ... Connecting to jsonplaceholder.typicode.com (jsonplaceholder.typicode.com)|104.21.10.8|:443... connected. HTTP request sent, awaiting response... 200 OK' Length: 600 [application/json] Saving to: ‘STDOUT’ - 0%[ ] 0 --.-KB/s [ { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipitnsuscipit recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto" }, { "userId": 1, "id": 2, "title": "qui est esse", "body": "est rerum tempore vitaensequi sint nihil reprehenderit dolor beatae ea dolores nequenfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendisnqui aperiam non debitis possimus qui neque nisi nulla" } - 100%[==================================>] 600 --.-KB/s in 0s 2021-07-21 16:52:53 (4.12 MB/s) - written to stdout [600/600]

      Notice the line where it says HTTP request sent, awaiting response... 200 OK, which means that you have successfully sent a GET request to JSONPlaceholder.

      If that is too much output you can use the -q option that you learned in the previous section to restrict the output to the results of the GET request:

      • wget -O- -q https://jsonplaceholder.typicode.com/posts?_limit=2

      The output will look similar to this:

      Output

      [ { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipitnsuscipit recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto" }, { "userId": 1, "id": 2, "title": "qui est esse", "body": "est rerum tempore vitaensequi sint nihil reprehenderit dolor beatae ea dolores nequenfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendisnqui aperiam non debitis possimus qui neque nisi nulla" } ]

      Sending POST requests

      Wget lets you send POST requests by running a command that looks like the following:

      • wget --method==[post] -O- --body-data=[ body in json format ] --header=[ String ] [ URL ]

      Run the following command:

      • wget --method=post -O- -q --body-data="{"title": "Wget POST","body": "Wget POST example body","userId":1}" --header=Content-Type:application/json https://jsonplaceholder.typicode.com/posts

      In the command above, you used wget to send a POST request to JSON Placeholder to create a new post. You set the method to post, the Header to Content-Type:application/json and sent the following request body to it :{"title": "Wget POST","body": "Wget POST example body","userId":1}.

      The output will look similar to this:

      Output

      { "title": "Wget POST", "body": "Wget POST example body", "userId": 1, "id": 101 }

      Sending PUT requests

      Wget lets you send PUT requests by running a command that looks like the following:

      • wget --method==[put] -O- --body-data=[ body in json format ] --header=[ String ] [ URL ]

      Run the following command:

      • wget --method=put -O- -q --body-data="{"title": "Wget PUT", "body": "Wget PUT example body", "userId": 1, "id":1}" --header=Content-Type:application/json https://jsonplaceholder.typicode.com/posts/1

      In the command above you used wget to send a PUT request to JSON Placeholder to edit the first post in this REST API. You set the method to put, the Header to Content-Type:application/json and sent the following request body to it :{"title": "Wget PUT", "body": "Wget PUT example body", "userId": 1, "id":1} .

      The output will look similar to this:

      Output

      { "body": "Wget PUT example body", "title": "Wget PUT", "userId": 1, "id": 1 }

      Sending DELETE requests

      Wget lets you send DELETE requests by running a command that looks like the following:

      • wget --method==[delete] -O- [ URL ]

      Run the following command:

      • wget --method=delete -O- -q --header=Content-Type:application/json https://jsonplaceholder.typicode.com/posts/1

      In the command above you used wget to send a DELETE request to JSON Placeholder to delete the first post in this REST API. You set the method to delete, and set the post you want to delete to 1 in the URL.

      The output will look similar to this:

      Output

      {}

      In this section, you learned how to use Wget to send GET, POST, PUT and DELETE requests with only one header field. In the next section, you will learn how to send multiple header fields in order to create and manage a Droplet in your DigitalOcean account.

      Creating and Managing a DigitalOcean Droplet

      In this section, you will apply what you learned in the previous section and use Wget to create and manage a Droplet in your DigitalOcean account. But before you do that, you will learn how to send multiple headers fields in a HTTP method.

      The syntax for a command to send multiple headers looks like this:

      • wget --header=[ first header ] --header=[ second header] --header=[ N header] [ URL ]

      You can have as many headers fields as you like by repeating the --header option as many times as you need.

      To create a Droplet or interact with any other resource in the DigitalOcean API, you will need to send two request headers:

      Content-Type: application/json
      Authorization: Bearer your_personal_access_token
      

      You already saw the first header in the previous section. The second header is what lets you authenticate your account. It has the String named Bearer followed by your DigitalOcean account Personal Access Token.

      Run the following command, replacing your_personal_access_token with your DigitalOcean Personal Access Token:

      • wget --method=post -O- -q --header="Content-Type: application/json" --header="Authorization: Bearer your_personal_access_token" --body-data="{"name":"Wget-example","region":"nyc1","size":"s-1vcpu-1gb","image":"ubuntu-20-04-x64","tags": ["Wget-tutorial"]}" https://api.digitalocean.com/v2/droplets

      With the command above, you have created an ubuntu-20-04-x64 Droplet in the nyc1 region named Wget-example with 1vcpu and 1gb of memory, and you have set the tag to Wget-tutorial. For more information about the attributes in the body-data field, see the DigitalOcean API documentation.

      The output will look similar to this:

      Output

      {"droplet":{"id":237171073,"name":"Wget-example","memory":1024,"vcpus":1,"disk":25,"locked":false,"status":"new","kernel":null,"created_at":"2021-03-16T12:38:59Z","features":[],"backup_ids":[],"next_backup_window":null,"snapshot_ids":[],"image":{"id":72067660,"name":"20.04 (LTS) x64","distribution":"Ubuntu","slug":"ubuntu-20-04-x64","public":true,"regions":["nyc3","nyc1","sfo1","nyc2","ams2","sgp1","lon1","ams3","fra1","tor1","sfo2","blr1","sfo3"],"created_at":"2020-10-20T16:34:30Z","min_disk_size":15,"type":"base","size_gigabytes":0.52,"description":"Ubuntu 20.04 x86","tags":[],"status":"available"},"volume_ids":[],"size":{"slug":"s-1vcpu-1gb","memory":1024,"vcpus":1,"disk":25,"transfer":1.0,"price_monthly":5.0,"price_hourly":0.00744,"regions":["ams2","ams3","blr1","fra1","lon1","nyc1","nyc2","nyc3","sfo1","sfo3","sgp1","tor1"],"available":true,"description":"Basic"},"size_slug":"s-1vcpu-1gb","networks":{"v4":[],"v6":[]},"region":{"name":"New York 1","slug":"nyc1","features":["backups","ipv6","metadata","install_agent","storage","image_transfer"],"available":true,"sizes":["s-1vcpu-1gb","s-1vcpu-1gb-intel","s-1vcpu-2gb","s-1vcpu-2gb-intel","s-2vcpu-2gb","s-2vcpu-2gb-intel","s-2vcpu-4gb","s-2vcpu-4gb-intel","s-4vcpu-8gb","c-2","c2-2vcpu-4gb","s-4vcpu-8gb-intel","g-2vcpu-8gb","gd-2vcpu-8gb","s-8vcpu-16gb","m-2vcpu-16gb","c-4","c2-4vcpu-8gb","s-8vcpu-16gb-intel","m3-2vcpu-16gb","g-4vcpu-16gb","so-2vcpu-16gb","m6-2vcpu-16gb","gd-4vcpu-16gb","so1_5-2vcpu-16gb","m-4vcpu-32gb","c-8","c2-8vcpu-16gb","m3-4vcpu-32gb","g-8vcpu-32gb","so-4vcpu-32gb","m6-4vcpu-32gb","gd-8vcpu-32gb","so1_5-4vcpu-32gb","m-8vcpu-64gb","c-16","c2-16vcpu-32gb","m3-8vcpu-64gb","g-16vcpu-64gb","so-8vcpu-64gb","m6-8vcpu-64gb","gd-16vcpu-64gb","so1_5-8vcpu-64gb","m-16vcpu-128gb","c-32","c2-32vcpu-64gb","m3-16vcpu-128gb","m-24vcpu-192gb","g-32vcpu-128gb","so-16vcpu-128gb","m6-16vcpu-128gb","gd-32vcpu-128gb","m3-24vcpu-192gb","g-40vcpu-160gb","so1_5-16vcpu-128gb","m-32vcpu-256gb","gd-40vcpu-160gb","so-24vcpu-192gb","m6-24vcpu-192gb","m3-32vcpu-256gb","so1_5-24vcpu-192gb"]},"tags":["Wget-tutorial"]},"links":{"actions":[{"id":1164336542,"rel":"create","href":"https://api.digitalocean.com/v2/actions/1164336542"}]}}

      If you see an output similar to the one above that means that you have successfully created a Droplet.

      Now let’s get a list of all the Droplets in your account that have the tag Wget-tutorial. Run the following command, replacing your_personal_access_token with your DigitalOcean Personal Access Token:

      • wget -O- -q --header="Content-Type: application/json" --header="Authorization: Bearer your_personal_access_token" https://api.digitalocean.com/v2/droplets?tag_name=Wget-tutorial

      You should see the name of the Droplet you have just created in the output:

      Output

      {"droplets":[{"id":237171073,"name":"Wget-example","memory":1024,"vcpus":1,"disk":25,"locked":false,"status":"active","kernel":null,"created_at":"2021-03-16T12:38:59Z","features":["private_networking"],"backup_ids":[],"next_backup_window":null,"snapshot_ids":[],"image":{"id":72067660,"name":"20.04 (LTS) x64","distribution":"Ubuntu","slug":"ubuntu-20-04-x64","public":true,"regions":["nyc3","nyc1","sfo1","nyc2","ams2","sgp1","lon1","ams3","fra1","tor1","sfo2","blr1","sfo3"],"created_at":"2020-10-20T16:34:30Z","min_disk_size":15,"type":"base","size_gigabytes":0.52,"description":"Ubuntu 20.04 x86","tags":[],"status":"available"},"volume_ids":[],"size":{"slug":"s-1vcpu-1gb","memory":1024,"vcpus":1,"disk":25,"transfer":1.0,"price_monthly":5.0,"price_hourly":0.00744,"regions":["ams2","ams3","blr1","fra1","lon1","nyc1","nyc2","nyc3","sfo1","sfo3","sgp1","tor1"],"available":true,"description":"Basic"},"size_slug":"s-1vcpu-1gb","networks":{"v4":[{"ip_address":"10.116.0.2","netmask":"255.255.240.0","gateway":"","type":"private"},{"ip_address":"204.48.20.197","netmask":"255.255.240.0","gateway":"204.48.16.1","type":"public"}],"v6":[]},"region":{"name":"New York 1","slug":"nyc1","features":["backups","ipv6","metadata","install_agent","storage","image_transfer"],"available":true,"sizes":["s-1vcpu-1gb","s-1vcpu-1gb-intel","s-1vcpu-2gb","s-1vcpu-2gb-intel","s-2vcpu-2gb","s-2vcpu-2gb-intel","s-2vcpu-4gb","s-2vcpu-4gb-intel","s-4vcpu-8gb","c-2","c2-2vcpu-4gb","s-4vcpu-8gb-intel","g-2vcpu-8gb","gd-2vcpu-8gb","s-8vcpu-16gb","m-2vcpu-16gb","c-4","c2-4vcpu-8gb","s-8vcpu-16gb-intel","m3-2vcpu-16gb","g-4vcpu-16gb","so-2vcpu-16gb","m6-2vcpu-16gb","gd-4vcpu-16gb","so1_5-2vcpu-16gb","m-4vcpu-32gb","c-8","c2-8vcpu-16gb","m3-4vcpu-32gb","g-8vcpu-32gb","so-4vcpu-32gb","m6-4vcpu-32gb","gd-8vcpu-32gb","so1_5-4vcpu-32gb","m-8vcpu-64gb","c-16","c2-16vcpu-32gb","m3-8vcpu-64gb","g-16vcpu-64gb","so-8vcpu-64gb","m6-8vcpu-64gb","gd-16vcpu-64gb","so1_5-8vcpu-64gb","m-16vcpu-128gb","c-32","c2-32vcpu-64gb","m3-16vcpu-128gb","m-24vcpu-192gb","g-32vcpu-128gb","so-16vcpu-128gb","m6-16vcpu-128gb","gd-32vcpu-128gb","m3-24vcpu-192gb","g-40vcpu-160gb","so1_5-16vcpu-128gb","m-32vcpu-256gb","gd-40vcpu-160gb","so-24vcpu-192gb","m6-24vcpu-192gb","m3-32vcpu-256gb","so1_5-24vcpu-192gb"]},"tags":["Wget-tutorial"],"vpc_uuid":"5ee0a168-39d1-4c60-a89c-0b47390f3f7e"}],"links":{},"meta":{"total":1}}

      Now let’s take the id of the Droplet you have created and use it to delete the Droplet. Run the following command, replacing your_personal_access_token with your DigitalOcean Personal Access Token and your_droplet_id with your Droplet id:

      • wget --method=delete -O- --header="Content-Type: application/json" --header="Authorization: Bearer your_personal_access_token" https://api.digitalocean.com/v2/droplets/your_droplet_id

      In the command above, you added your Droplet id to the URL to delete it. If you are seeing a 204 No Content in the output, that means that you succeeded in deleting the Droplet.

      In this section, you used Wget to send multiple headers. Then, you created and managed a Droplet in your DigitalOcean account.

      Conclusion

      In this tutorial, you used Wget to download files in stable and unstable network conditions and interact with REST API endpoints. You then used this knowledge to create and manage a Droplet in your DigitalOcean account. If you would like to learn more about Wget, visit this tool’s manual page. For more Linux command-line tutorials visit DigitalOcean community tutorials.



      Source link

      Building a REST API With Django REST Framework


      How to Join

      This Tech Talk is free and open to everyone. Register below to get a link to join the live stream or receive the video recording after it airs.

      DateTimeRSVP
      April 28, 202111:00–12:00 p.m. ET / 3:00–4:00 p.m. GMT

      About the Talk

      The Django REST Framework is a powerful toolkit for building RESTful APIs on top of the popular Python framework Django. With its browsable API, robust authentication policies, and object serialization, it offers an amazing experience for rapidly creating REST APIs. Let’s get our hands dirty and build some APIs with DRF!

      What You’ll Learn

      • How to install the Django REST Framework
      • How to authenticate against the DRF
      • How to quickly create a CRUD based REST API

      This Talk Is Designed For

      Developers who want to build robust RESTful APIs using Python.

      Prerequisites

      A basic understanding of the Python programming language.

      Resources

      Django REST framework quickstart

      To join the live Tech Talk, register here.



      Source link

      Cómo crear una API de REST con Prisma y PostgreSQL


      El autor seleccionó la organización Diversity in Tech Fund para que reciba una donación como parte del programa Write for DOnations.

      Introducción

      Prisma es un conjunto de herramientas para bases de datos de código abierto. Consta de tres herramientas principales:

      • Prisma Client: un generador de consultas con seguridad de tipos que se genera de forma automática para Node.js y TypeScript.
      • Prisma Migrate: un sistema de migración y modelado de datos declarativo.
      • Prisma Studio: una GUI para ver y editar datos en su base de datos.

      Estas herramientas pretenden aumentar la productividad de los desarrolladores de aplicaciones en los flujos de trabajo de sus bases de datos. Uno de los principales beneficios de Prisma es el nivel de abstracción que proporciona: en lugar de tener que resolver consultas SQL o migraciones de esquemas complejas, los desarrolladores de aplicaciones pueden razonar acerca de sus datos de forma más intuitiva al utilizar Prisma para trabajar con su base de datos.

      En este tutorial, creará una API de REST para una aplicación de blog pequeña en TypeScript usando Prisma y una base de datos PostgreSQL. Configurará su base de datos PostgreSQL de forma local con Docker e implementará las rutas de la API de REST utilizando Express. Al final del tutorial, tendrá un servidor web que puede responder a varias solicitudes HTTP y leer y escribir datos en la base de datos ejecutándose en su equipo de forma local.

      Requisitos previos

      Para seguir este tutorial, necesitará lo siguiente:

      Es útil, pero no un requisito de este tutorial, tener conocimientos básicos sobre TypeScript y las API de REST.

      Paso 1: Crear su proyecto de TypeScript

      En este paso, configurará un proyecto de TypeScript simple utilizando npm. Este proyecto será la base para la API de REST que creará en el transcurso de este tutorial.

      Primero, cree un directorio nuevo para su proyecto:

      Luego, diríjase al directorio e inicie un proyecto npm vacío. Tenga en cuenta que la opción -y se utiliza para omitir las solicitudes interactivas del comando. Para verlas, elimine -y del comando:

      Para obtener más información sobre estas solicitudes, siga el Paso 1 de Cómo usar módulos Node.js con npm y package.json.

      Obtendrá un resultado similar al siguiente con las respuestas predeterminadas:

      Output

      Wrote to /.../my-blog/package.json: { "name": "my-blog", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo "Error: no test specified" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }

      Este comando crea un archivo package.json mínimo que utiliza como archivo de configuración de su proyecto npm. Con esto, está listo para configurar TypeScript en su proyecto.

      Ejecute el siguiente comando para realizar la instalación básica de TypeScript:

      • npm install typescript ts-node @types/node --save-dev

      Este comando instala tres paquetes como dependencias de desarrollo en su proyecto:

      • typescript: la cadena de herramientas de TypeScript.
      • ts-node: un paquete para ejecutar aplicaciones TypeScript sin compilar previamente a JavaScript.
      • @types/node: las definiciones de tipo de TypeScript para Node.js.

      Solo resta añadir un archivo tsconfig.json para garantizar que TypeScript esté configurado de forma adecuada para la aplicación que va a crear.

      Primero, ejecute el siguiente comando para crear el archivo:

      Agregue el siguiente código de JSON al archivo:

      my-blog/tsconfig.json

      {
        "compilerOptions": {
          "sourceMap": true,
          "outDir": "dist",
          "strict": true,
          "lib": ["esnext"],
          "esModuleInterop": true
        }
      }
      

      Guarde el archivo y ciérrelo.

      Esta es una configuración estándar y mínima para un proyecto de TypeScript. Puede encontrar información sobre las propiedades individuales del archivo de configuración en la documentación de TypeScript.

      Ha configurado su proyecto de TypeScript simple usando npm. A continuación, configurará su base de datos PostgreSQL con Docker y la conectará a Prisma.

      Paso 2: Configurar Prisma con PostgreSQL

      En este paso, instalará la CLI de Prisma, creará su archivo de esquema de Prisma inicial, configurará PostgreSQL con Docker y conectará Prisma a la base de datos. El archivo de esquema de Prisma es el archivo de configuración principal de su instalación de Prisma y contiene el esquema de su base de datos.

      Comience por instalar la CLI de Prisma con el siguiente comando:

      • npm install @prisma/cli --save-dev

      Se recomienda instalar la CLI de Prisma en el proyecto de forma local (en lugar de realizar una instalación global). Esto ayuda a evitar conflictos de versiones en caso de que tenga más de un proyecto de Prisma en su equipo.

      A continuación, configurará su base de datos PostgreSQL utilizando Docker. Cree un nuevo archivo de Docker Compose con el siguiente comando:

      Luego, añada el siguiente código al archivo nuevo:

      my-blog/docker-compose.yml

      version: '3.8'
      services:
        postgres:
          image: postgres:10.3
          restart: always
          environment:
            - POSTGRES_USER=sammy
            - POSTGRES_PASSWORD=your_password
          volumes:
            - postgres:/var/lib/postgresql/data
          ports:
            - '5432:5432'
      volumes:
        postgres:
      

      Este archivo de Docker Compose configura una base de datos PostgreSQL a la que se puede acceder a través del puerto 5432 del contenedor de Docker. Tenga en cuenta que estamos utilizando las credenciales de la base de datos sammy (usuario) y your_password (contraseña). Puede modificar estas credenciales y utilizar el nombre de usuario y la contraseña que desee. Guarde el archivo y ciérrelo.

      Ahora que estableció esta configuración, proceda a iniciar el servidor de la base de datos PostgreSQL con el siguiente comando:

      El resultado de este comando será similar al siguiente:

      Output

      Pulling postgres (postgres:10.3)... 10.3: Pulling from library/postgres f2aa67a397c4: Pull complete 6de83ca23e55: Pull complete . . . Status: Downloaded newer image for postgres:10.3 Creating my-blog_postgres_1 ... done

      Puede verificar que el servidor de la base de datos se esté ejecutando con el siguiente comando:

      Obtendrá un resultado similar al siguiente:

      Output

      CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 8547f8e007ba postgres:10.3 "docker-entrypoint.s…" 3 seconds ago Up 2 seconds 0.0.0.0:5432->5432/tcp my-blog_postgres_1

      Ahora que el servidor de la base de datos está en ejecución, puede crear su instalación de Prisma. Ejecute el siguiente comando desde la CLI de Prisma:

      Esto imprimirá el siguiente resultado:

      Output

      ✔ Your Prisma schema was created at prisma/schema.prisma. You can now open it in your favorite editor.

      Tenga en cuenta que es recomendable prefijar todas las invocaciones de la CLI de Prisma con npx. Esto garantiza que se utilice su instalación local.

      Cuando ejecutó el comando, la CLI de Prisma creó una nueva carpeta denominada prisma en su proyecto. Contiene estos dos archivos:

      • schema.prisma: el archivo de configuración principal de su proyecto de Prisma (incluirá su modelo de datos).
      • .env: un archivo dotenv para definir la URL de conexión de su base de datos.

      Para asegurarse de que Prisma conozca la ubicación de su base de datos, abra el archivo .env y ajuste la variable de entorno DATABASE_URL.

      Primero, abra el archivo .env:

      Ahora, puede establecer la variable de entorno de la siguiente manera:

      my-blog/prisma/.env

      DATABASE_URL="postgresql://sammy:your_password@localhost:5432/my-blog?schema=public"
      

      Asegúrese de reemplazar las credenciales de la base de datos por las que especificó en el archivo de Docker Compose. Para obtener más información sobre el formato de la URL de conexión, consulte la documentación de Prisma.

      Cuando termine, guarde y cierre el archivo.

      En este paso, configuró su base de datos PostgreSQL con Docker, instaló la CLI de Prisma y conectó a la base de datos a través de una variable de entorno. En la siguiente sección, definirá el modelo de datos y creará las tablas de su base de datos.

      Paso 3: Definir el modelo de datos y crear tablas de datos

      En este paso, definirá el modelo de datos en el archivo de esquema de Prisma. Luego, asignará ese modelo de datos a la base de datos con Prisma Migrate, que generará y enviará las instrucciones SQL para crear las tablas correspondientes a su modelo de datos. Como está creando una aplicación de blog, las principales entidades de la aplicación serán usuarios y publicaciones.

      Prisma utiliza su propio lenguaje de modelado de datos para definir la forma de los datos de su aplicación.

      Primero, abra el archivo schema.prisma con el siguiente comando:

      • nano prisma/schema.prisma

      Luego, añada las siguientes definiciones del modelo allí. Puede colocar los modelos en la parte inferior del archivo, justo después del bloque generator client:

      my-blog/prisma/schema.prisma

      . . .
      model User {
        id    Int     @default(autoincrement()) @id
        email String  @unique
        name  String?
        posts Post[]
      }
      
      model Post {
        id        Int     @default(autoincrement()) @id
        title     String
        content   String?
        published Boolean @default(false)
        author    User?   @relation(fields: [authorId], references: tag:www.digitalocean.com,2005:/community/tutorials/how-to-build-a-rest-api-with-prisma-and-postgresql-es)
        authorId  Int?
      }
      

      Guarde el archivo y ciérrelo.

      Está definiendo dos modelos, denominados User y Post. Cada uno de ellos contiene varios campos que representan las propiedades del modelo. Los modelos se asignarán a las tablas de la base de datos; los campos representan las columnas individuales.

      Tenga en cuenta que hay una relación de uno a varios entre los dos modelos, especificada por los campos de relaciones posts y author en User y Post. Esto significa que se puede asociar un usuario a varias publicaciones.

      Ahora que estableció estos modelos, puede crear las tablas correspondientes en la base de datos utilizando Prisma Migrate. Ejecute el siguiente comando en su terminal:

      • npx prisma migrate save --experimental --create-db --name "init"

      Este comando crea una migración nueva en su sistema de archivos. A continuación, se presenta una descripción general de las tres opciones que se proporcionan al comando:

      • --experimental: se requiere porque, actualmente, Prisma Migrate está en estado experimental.
      • --create-db: permite a Prisma Migrate crear la base de datos denominada my-blog especificada en la URL de conexión.
      • --name "init": especifica el nombre de la migración (se utilizará para dar nombre a la carpeta de migración que se crea en su sistema de archivos).

      El resultado de este comando será similar al siguiente:

      Output

      New datamodel: // This is your Prisma schema file, // learn more about it in the docs: https://pris.ly/d/prisma-schema datasource db { provider = "postgresql" url = env("DATABASE_URL") } generator client { provider = "prisma-client-js" } model User { id Int @default(autoincrement()) @id email String @unique name String? posts Post[] } model Post { id Int @default(autoincrement()) @id title String content String? published Boolean @default(false) author User? @relation(fields: [authorId], references: tag:www.digitalocean.com,2005:/community/tutorials/how-to-build-a-rest-api-with-prisma-and-postgresql-es) authorId Int? } Prisma Migrate just created your migration 20200811140708-init in migrations/ └─ 20200811140708-init/ └─ steps.json └─ schema.prisma └─ README.md

      Puede ver los archivos de migración que se crearon en el directorio prisma/migrations.

      Para ejecutar la migración de su base de datos y crear las tablas para sus modelos de Prisma, ejecute el siguiente comando en su terminal:

      • npx prisma migrate up --experimental

      Obtendrá el siguiente resultado:

      Output

      . . . Checking the datasource for potential data loss... Database Changes: Migration Database actions Status 20200811140708-init 2 CreateTable statements. Done 🚀 You can get the detailed db changes with prisma migrate up --experimental --verbose Or read about them here: ./migrations/20200811140708-init/README.md 🚀 Done with 1 migration in 206ms.

      Ahora, Prisma Migrate generará las instrucciones SQL necesarias para la migración y las enviará a la base de datos. Estas son las instrucciones SQL que crearon las tablas:

      CREATE TABLE "public"."User" (
        "id" SERIAL,
        "email" text  NOT NULL ,
        "name" text   ,
        PRIMARY KEY ("id")
      )
      
      CREATE TABLE "public"."Post" (
        "id" SERIAL,
        "title" text  NOT NULL ,
        "content" text   ,
        "published" boolean  NOT NULL DEFAULT false,
        "authorId" integer   ,
        PRIMARY KEY ("id")
      )
      
      CREATE UNIQUE INDEX "User.email" ON "public"."User"("email")
      
      ALTER TABLE "public"."Post" ADD FOREIGN KEY ("authorId")REFERENCES "public"."User"("id") ON DELETE SET NULL ON UPDATE CASCADE
      

      En este paso, definió su modelo de datos en el esquema de Prisma y creó las respectivas tablas de bases de datos con Prisma Migrate. En el siguiente paso, instalará Prisma Client en su proyecto para poder consultar la base de datos.

      Paso 4: Explorar consultas de Prisma Client en una secuencia de comandos simple

      Prisma Client es un generador de consultas con seguridad de tipos de generación automática que puede utilizar para leer y escribir datos mediante programación en una base de datos desde una aplicación Node.js o TypeScript. Lo utilizará para acceder a la base de datos con las rutas de su API de REST, en lugar de usar ORM tradicionales, consultas SQL simples, capas de acceso a datos personalizadas o cualquier otro método de comunicación con una base de datos.

      En este paso, instalará Prisma Client y se familiarizará con las consultas que puede enviar. Antes de implementar las rutas de su API de REST en los siguientes pasos, analizaremos algunas consultas de Prisma Client en una secuencia de comandos ejecutable simple.

      Primero, para instalar Prisma Client en su proyecto, abra su terminal e instale el paquete npm de Prisma Client:

      • npm install @prisma/client

      A continuación, cree un directorio nuevo denominado src para alojar sus archivos de origen:

      Ahora, cree un archivo de TypeScript en el directorio nuevo:

      Todas las consultas de Prisma Client devuelven promesas con las que puede usar await en su código. Para hacerlo, deberá enviar las consultas dentro de una función async.

      Añada el siguiente código reutilizable con una función async que se ejecute en su secuencia de comandos:

      my-blog/src/index.ts

      import { PrismaClient } from '@prisma/client'
      
      const prisma = new PrismaClient()
      
      async function main() {
        // ... your Prisma Client queries will go here
      }
      
      main()
        .catch((e) => console.error(e))
        .finally(async () => await prisma.disconnect())
      

      A continuación, se presenta una descripción general del código reutilizable:

      1. Se importa el constructor PrismaClient del paquete npm @prisma/client previamente instalado.
      2. Se inicia PrismaClient al invocar al constructor y se obtiene una instancia denominada prisma.
      3. Se define una función async denominada main en la que, a continuación, añadirá las consultas de Prisma Client.
      4. Se invoca la función main y, a la vez, se detectan posibles excepciones y se garantiza que Prisma Client cierre cualquier conexión con bases de datos abierta al invocar prisma.disconnect().

      Ahora que estableció la función main, puede comenzar a añadir consultas de Prisma Client a la secuencia de comandos. Ajuste index.ts para que tenga el siguiente aspecto:

      my-blog/src/index.ts

      import { PrismaClient } from '@prisma/client'
      
      const prisma = new PrismaClient()
      
      async function main() {
        const newUser = await prisma.user.create({
          data: {
            name: 'Alice',
            email: '[email protected]',
            posts: {
              create: {
                title: 'Hello World',
              },
            },
          },
        })
        console.log('Created new user: ', newUser)
      
        const allUsers = await prisma.user.findMany({
          include: { posts: true },
        })
        console.log('All users: ')
        console.dir(allUsers, { depth: null })
      }
      
      main()
        .catch((e) => console.error(e))
        .finally(async () => await prisma.disconnect())
      

      En este código, está utilizando dos consultas de Prisma Client:

      • create: crea un nuevo registro de User. Tenga en cuenta que, en realidad, está utilizando una escritura anidada, lo que significa que está creando un registro de User y uno de Post en la misma consulta.
      • findMany: lee todos los registros de User existentes de la base de datos. Está proporcionando una opción include, que, adicionalmente, carga los registros de Post relacionados de cada registro de User.

      A continuación, ejecute la secuencia de comandos con el siguiente comando:

      Obtendrá el siguiente resultado en su terminal:

      Output

      Created new user: { id: 1, email: '[email protected]', name: 'Alice' } [ { id: 1, email: '[email protected]', name: 'Alice', posts: [ { id: 1, title: 'Hello World', content: null, published: false, authorId: 1 } ] }

      Nota: Si está utilizando una GUI de base de datos, puede verificar que los datos se hayan creado al revisar las tablas User y Post. De forma alternativa, puede consultar los datos de Prisma Studio al ejecutar npx prisma studio --experimental.

      Ha aprendido a utilizar Prisma Client para leer y escribir datos en su base de datos. En los siguientes pasos, aplicará sus conocimientos nuevos para implementar las rutas de una API de REST de muestra.

      Paso 5: Implementar su primera ruta de la API de REST

      En este paso, instalará Express en su aplicación. Express es un marco web popular para Node.js que utilizará para implementar sus rutas de la API de REST en este proyecto. La primera ruta que implementará le permitirá obtener todos los usuarios de la API utilizando una solicitud GET. Obtendrá los datos de los usuarios de la base de datos utilizando Prisma Client.

      Instale Express con el siguiente comando:

      Como está utilizando TypeScript, también le convendrá instalar los respectivos tipos como dependencias de desarrollo. Para hacerlo, ejecute el siguiente comando:

      • npm install @types/express --save-dev

      Ahora que estableció las dependencias, puede configurar su aplicación Express.

      Comience por volver a abrir su archivo de origen principal:

      A continuación, elimine todo el código de index.ts y sustitúyalo por el siguiente para iniciar su API de REST:

      my-blog/src/index.ts

      import { PrismaClient } from '@prisma/client'
      import express from 'express'
      
      const prisma = new PrismaClient()
      const app = express()
      
      app.use(express.json())
      
      // ... your REST API routes will go here
      
      app.listen(3000, () =>
        console.log('REST API server ready at: http://localhost:3000'),
      )
      

      A continuación, se presenta una descripción breve del código:

      1. Se importan PrismaClient y express de sus respectivos paquetes npm.
      2. Se inicia PrismaClient al invocar al constructor y se obtiene una instancia denominada prisma.
      3. Su aplicación Express se crea al invocar express().
      4. Se añade el software intermedio express.json() para garantizar que Express pueda procesar correctamente los datos de JSON.
      5. Se inicia el servidor en el puerto 3000.

      Con esto, puede implementar su primera ruta. Agregue el siguiente código entre las invocaciones a app.use y app.listen:

      my-blog/src/index.ts

      . . .
      app.use(express.json())
      
      app.get('/users', async (req, res) => {
        const users = await prisma.user.findMany()
        res.json(users)
      })
      
      app.listen(3000, () =>
      console.log('REST API server ready at: http://localhost:3000'),
      )
      

      Una vez que lo haya añadido, guarde y cierre su archivo. A continuación, inicie su servidor web local utilizando el siguiente comando:

      Recibirá el siguiente resultado:

      Output

      REST API server ready at: http://localhost:3000

      Para acceder a la ruta /users, puede apuntar su navegador a http://localhost:3000/users o a cualquier otro cliente HTTP.

      En este tutorial, probará todas las rutas de la API de REST utilizando curl, un cliente HTTP basado en terminal.

      Nota: Si prefiere usar un cliente HTTP basado en GUI, puede usar alternativas como Postwoman o el cliente REST avanzado.

      Para probar su ruta, abra una ventana o una pestaña de terminal nueva (para que su servidor web local pueda seguir en ejecución) y ejecute el siguiente comando:

      • curl http://localhost:3000/users

      Obtendrá los datos de User que creó en el paso anterior:

      Output

      [{"id":1,"email":"[email protected]","name":"Alice"}]

      Tenga en cuenta que la matriz posts no se incluye en este momento. Esto se debe a que no está pasando la opción include a la invocación de findMany en la implementación de la ruta /users.

      Ha implementado su primera ruta de la API de REST en /users. En el siguiente paso, implementará las rutas restantes de la API de REST para añadir más funcionalidad a su API.

      Paso 6: Implementar las rutas restantes de la API de REST

      En este paso, implementará las rutas restantes de la API de REST para su aplicación de blog. Al final, su servidor web proporcionará diversas solicitudes GET, POST, PUT y DELETE.

      A continuación, se presenta una descripción general de las diferentes rutas que implementará:

      Método HTTPRutaDescripción
      GET/feedObtiene todas las publicaciones publicadas.
      GET/post/:idObtiene un publicación específica por su ID.
      POST/userCrea un usuario nuevo.
      POST/postCrea una publicación nueva (como borrador).
      PUT/post/publish/:idEstablece el campo published de una publicación en true.
      DELETEpost/:idElimina una publicación por su ID.

      Primero, proceda a ejecutar e implementar las rutas GET restantes.

      Abra index.ts con el siguiente comando:

      A continuación, añada el siguiente código después de la implementación de la ruta /users:

      my-blog/src/index.ts

      . . .
      
      app.get('/feed', async (req, res) => {
        const posts = await prisma.post.findMany({
          where: { published: true },
          include: { author: true }
        })
        res.json(posts)
      })
      
      app.get(`/post/:id`, async (req, res) => {
        const { id } = req.params
        const post = await prisma.post.findOne({
          where: { id: Number(id) },
        })
        res.json(post)
      })
      
      app.listen(3000, () =>
        console.log('REST API server ready at: http://localhost:3000'),
      )
      

      Guarde y cierre su archivo.

      Este código implementa las rutas de la API para dos solicitudes GET:

      • /feed: devuelve una lista de las publicaciones publicadas.
      • /post/:id: devuelve una publicación específica por su ID.

      Se utiliza Prisma Client en ambas implementaciones. En la implementación de la ruta /feed, la consulta que envía con Prisma Client filtra todos los registros de Post en los que la columna published contiene el valor true. Además, la consulta de Prisma Client utiliza include para obtener la información relacionada de author de cada publicación que se devuelve. En la implementación de la ruta /post/:id, pasa la ID que se obtiene de la ruta de la URL para poder leer un registro de Post específico de la base de datos.

      Puede detener el servidor al pulsar CTRL+C en el teclado. A continuación, reinicie el servidor utilizando lo siguiente:

      Para probar la ruta /feed, puede usar el siguiente comando curl:

      • curl http://localhost:3000/feed

      Como aún no se ha publicado ninguna publicación, la respuesta es una matriz vacía:

      Output

      []

      Para probar la ruta /post/:id, puede usar el siguiente comando curl:

      • curl http://localhost:3000/post/1

      Este comando devolverá la publicación que creó inicialmente:

      Output

      {"id":1,"title":"Hello World","content":null,"published":false,"authorId":1}

      A continuación, ejecute las dos rutas de POST. Añada el siguiente código a index.ts después de las implementaciones de las tres rutas de GET:

      my-blog/src/index.ts

      . . .
      
      app.post(`/user`, async (req, res) => {
        const result = await prisma.user.create({
          data: { ...req.body },
        })
        res.json(result)
      })
      
      app.post(`/post`, async (req, res) => {
        const { title, content, authorEmail } = req.body
        const result = await prisma.post.create({
          data: {
            title,
            content,
            published: false,
            author: { connect: { email: authorEmail } },
          },
        })
        res.json(result)
      })
      
      app.listen(3000, () =>
        console.log('REST API server ready at: http://localhost:3000'),
      )
      

      Cuando termine, guarde y cierre el archivo.

      Este código implementa las rutas de la API para dos solicitudes POST:

      • /user: crea un usuario nuevo en la base de datos.
      • /post: crea una publicación nueva en la base de datos.

      Al igual que anteriormente, se utiliza Prisma Client en ambas implementaciones. En la implementación de la ruta /user, pasa los valores del cuerpo de la solicitud HTTP a la consulta create de Prisma Client.

      La ruta /post es un poco más compleja: como no puede pasar los valores del cuerpo de la solicitud HTTP directamente, primero, deberá extraerlos de forma manual para pasarlos a la consulta de Prisma Client. Esto se debe a que la estructura de JSON en el cuerpo de la solicitud no coincide con la que espera Prisma Client, por lo tanto, debe crear la estructura esperada de forma manual.

      Puede probar las rutas nuevas al detener el servidor con CTRL+C. A continuación, reinicie el servidor utilizando lo siguiente:

      Para crear un usuario nuevo a través de la ruta /user, puede enviar la siguiente solicitud POST con curl:

      • curl -X POST -H "Content-Type: application/json" -d '{"name":"Bob", "email":"[email protected]"}' http://localhost:3000/user

      Con esto, se creará un usuario nuevo en la base de datos y se imprimirá el siguiente resultado:

      Output

      {"id":2,"email":"[email protected]","name":"Bob"}

      Para crear una publicación nueva a través de la ruta /post, puede enviar la siguiente solicitud POST con curl:

      • curl -X POST -H "Content-Type: application/json" -d '{"title":"I am Bob", "authorEmail":"[email protected]"}' http://localhost:3000/post

      Con esto, se creará una publicación nueva en la base de datos que se conectará al usuario con el correo electrónico [email protected]. Se imprime el siguiente resultado:

      Output

      {"id":2,"title":"I am Bob","content":null,"published":false,"authorId":2}

      Por último, puede implementar las rutas PUT y DELETE.

      Abra index.ts con el siguiente comando:

      A continuación, después de la implementación de las dos rutas de POST, añada el código resaltado:

      my-blog/src/index.ts

      . . .
      
      app.put('/post/publish/:id', async (req, res) => {
        const { id } = req.params
        const post = await prisma.post.update({
          where: { id: Number(id) },
          data: { published: true },
        })
        res.json(post)
      })
      
      app.delete(`/post/:id`, async (req, res) => {
        const { id } = req.params
        const post = await prisma.post.delete({
          where: { id: Number(id) },
        })
        res.json(post)
      })
      
      app.listen(3000, () =>
        console.log('REST API server ready at: http://localhost:3000'),
      )
      

      Guarde y cierre su archivo.

      Este código implementa las rutas de la API para una solicitud PUT y una DELETE:

      • /post/public/:id (PUT): publica una publicación por su ID.
      • /post/:id (DELETE): elimina una publicación por su ID.

      Nuevamente, se utiliza Prisma Client en ambas implementaciones. En la implementación de la ruta /post/public/:id, se obtiene la ID de la publicación que se va a publicar de la URL y se pasa a la consulta update de Prisma Client. La implementación de la ruta /post/:id para eliminar una publicación de la base de datos también obtiene la ID de la publicación de la URL y la pasa a la consulta delete de Prisma Client.

      Vuelva a detener el servidor pulsando CTRL+C en el teclado. A continuación, reinicie el servidor utilizando lo siguiente:

      Puede probar la ruta PUT con el siguiente comando curl:

      • curl -X PUT http://localhost:3000/post/publish/2

      Con esto, se publicará la publicación con un valor de ID de 2. Si reenvía la solicitud /feed, ahora, esta publicación se incluirá en la respuesta.

      Por último, puede probar la ruta DELETE con el siguiente comando curl:

      • curl -X DELETE http://localhost:3000/post/1

      Con esto, se eliminará la publicación con un valor de ID de 1. Para confirmar que la publicación con esta ID se haya eliminado, puede reenviar una solicitud GET a la ruta /post/1.

      En este paso, implementó las rutas restantes de la API de REST para su aplicación de blog. Ahora, la API responde a diversas solicitudes GET, POST, PUT y DELETE e implementa la funcionalidad para leer y escribir datos en la base de datos.

      Conclusión

      En este artículo, creó un servidor para la API de REST con diversas rutas para crear, leer, actualizar y eliminar datos de usuarios y publicaciones para una aplicación de blog. Está utilizando Prisma Client dentro de las rutas de la API para enviar las consultas respectivas a su base de datos.

      Como próximo paso, puede implementar rutas de la API adicionales o ampliar el esquema de su base de datos utilizando Prisma Migrate. Asegúrese de consultar la documentación de Prisma para obtener más información sobre los distintos aspectos de Prisma y explorar algunos proyectos de ejemplo listos para ejecutar en el repositorio prisma-examples utilizando herramientas como GraphQL o API de grPC.



      Source link