Last active
June 24, 2024 18:24
-
-
Save CodeByAidan/fcf2d7ddcc456fa060631d24abb477f5 to your computer and use it in GitHub Desktop.
An example using a GET HTTP call and parsing the result (with concurrency) in JSON via serialization. All using Crystal!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require "http/client" | |
| require "json" | |
| class Geo | |
| include JSON::Serializable | |
| property lat : String | |
| property lng : String | |
| end | |
| class Address | |
| include JSON::Serializable | |
| property street : String | |
| property suite : String | |
| property city : String | |
| property zipcode : String | |
| property geo : Geo | |
| end | |
| class Company | |
| include JSON::Serializable | |
| property name : String | |
| property catchPhrase : String | |
| property bs : String | |
| end | |
| class User | |
| include JSON::Serializable | |
| property id : Int32 | |
| property name : String | |
| property username : String | |
| property email : String | |
| property address : Address | |
| property phone : String | |
| property website : String | |
| property company : Company | |
| end | |
| def process_user_data(user : User) | |
| puts "ID: #{user.id}, Name: #{user.name}, Email: #{user.email}" | |
| end | |
| url = "https://jsonplaceholder.typicode.com/users" | |
| response = HTTP::Client.get(url) | |
| if response.status_code == 200 | |
| users = Array(User).from_json(response.body) | |
| channel = Channel(Nil).new | |
| users.each do |user| | |
| spawn do | |
| process_user_data(user) | |
| channel.send(nil) | |
| end | |
| end | |
| users.size.times do | |
| channel.receive | |
| end | |
| else | |
| puts "Failed to fetch data: #{response.status_code}" | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ID: 1, Name: Leanne Graham, Email: Sincere@april.biz | |
| ID: 2, Name: Ervin Howell, Email: Shanna@melissa.tv | |
| ID: 3, Name: Clementine Bauch, Email: Nathan@yesenia.net | |
| ID: 4, Name: Patricia Lebsack, Email: Julianne.OConner@kory.org | |
| ID: 5, Name: Chelsey Dietrich, Email: Lucio_Hettinger@annie.ca | |
| ID: 6, Name: Mrs. Dennis Schulist, Email: Karley_Dach@jasper.info | |
| ID: 7, Name: Kurtis Weissnat, Email: Telly.Hoeger@billy.biz | |
| ID: 8, Name: Nicholas Runolfsdottir V, Email: Sherwood@rosamond.me | |
| ID: 9, Name: Glenna Reichert, Email: Chaim_McDermott@dana.io | |
| ID: 10, Name: Clementina DuBuque, Email: Rey.Padberg@karina.biz |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment