iOS Swift 5 Tutorial: Make HTTP POST Requests to an API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi and welcome to another very exciting tutorial today we're going to have a look at how we can actually make API requests and send information to this API so actually making post requests or HTTP POST requests and therefore I have created this little demo application that lets me create a new message once I hit Send this is going to be sent to a quick little API that I created for this video and when I reload my page here on the Left I get a new message right here so we're making HTTP post requests and I'm just going to use my favorite application for things like that called wrested to illustrate what we're doing so my API is running at local host and port 8080 and what I can do here in wrested is configuring what kind of request I'd like to send so first of all I'm going to check a quick get request using my extension or my endpoint API and messages and once I sent this request I get a nice little response here telling me with the code 200 that everything is okay we were saving this as JSON code and I'm receiving it right here so I have an ID for my message and I have this message key that gives me actually my message so if you'd like to do this the other way around we're actually using the same API endpoint that I've created but we're using a post request and what I'd like to do is send some information to this API and what I have to do here in wrested is choosing the correct encoding formats so we're using a JSON encoded format and what we're going to send is one parameter which has the key message and the value is for example a second message and once I sent this to my API I get another response off okay we're again having the content type of application JSON and we also get the message that we send as a response so once I reload my page as you can see there is my response and so that we do not have to do this using wrested I'm going to show you how to do this in an iOS application if you're interested to learn how to actually write an API such as this and the The Associated application our website that comes with it then you can use the link in the video description below to actually enter your email so that I can notify you once my vapor course is ready so everything I did here with the API is created in labor are with the vapor framework and Xcode and Swift very cool if you're interested to learn how to create an API such as this and also how to actually make this secure because this is everything but secure we shouldn't you should be able to just send a post request to an API with all without authentication that's that's that's not the best thing to do but anyways this is just for a demo purposes so I just didn't put too much effort into it just to show you how to actually make post requests to an API but if you're interested to learn how to do this the right way and how to actually create an API web application and so on with Swift and vapor then just enter your email using the google form in the video description below and to actually create this fine little sample app that I have here I'm going to show you the execute project that I am using just a very simple view controller here with this one tiny old button in the center and the view controller also only has this one IB action that is associated with the button once you hit the button I'm creating an alert controller that has a textfield you have a cancel button you have a send button and once you press send we're checking if we actually have text entered into our text field and then we're displaying the alert controller and actually here we're going to make the request to our API but of course we were having this API request struct where we have the appropriate code to actually outsource the API request and what we also have is a little message class that is the model for our message of course it's a very simple model we just have this message string or this message text we have the ID we have an initializer and the most important aspect for this whole thing is that this message class is codable you have actually encode about as a protocol and you have decodable as a protocol and codable gives you the abilities of encode a bowl and decodable so that you can both encode things to send them to an API and also receive things and decode things that you get from the API so for example JSON encoded so what we are going to do now is opening up our API request we're using Swift five here so I have just defined an API era and numeration where I have just defined some error cases that I could think of there could be more they could also be more expressive but for this tutorial it'll do and what we're going to do here in this struct is just defining a resource URL we are initializing our API extract with an API endpoint in that case messages you could also have depending on your API as something else but obviously we're having the API running at localhost port 8080 API and so on and just also notice that I'm using a standard HTTP connection here so this is not secure and what I had to do to make this work is actually allow arbitrary loads just added this key and the key have transport security settings in my info pls so that I can really work with that stared HTTP requests because this is a requirement if you're not using secure HTTP connections so with that we have the initializer that actually initialize also our resource URL that we're now going to use to create a safe function for our messages to be saved and what we want to do here is actually save a message so this is off type message and we also again need a completion Handler or a completion closure which is escaping to learn more about that you can also check out my last video where you can learn all of that in a little more detail but just with a get request and not with a post request so since we are working with Swift 5 we have this awesome result type that we can use to actually return or to include a message in case of a success and an API era is something went wrong so very neat type that we can use here and we actually just wanted to return void here and what our function does is actually pretty simple but at many points we could run into error so we're using do and try and catch here so first of all what we need to do is create a URL request so just using URL request and initialize that with our resource URL and now we come to the interesting part that you don't have to do actually when you just create a get request because what we have to do is actually define that we'd like to use an HT team method of HTTP method of post and what we also have to do is set the HTTP header field content type and set this to application JSON so this is the first these are the first two things that we're going to you do taking our URL request and lower case you URL request set the HTTP method to post and then we're going to use the URL request again add a value for a specific HTTP header field and we're using application JSON for the field content type so this these are the first two steps and now what we have to do is the find the HTTP body of our URL request and this is going to include our message to save as JSON code so we are using the URL request again and defining the HTTP body in this case and this is where things could go wrong so we're trying to use the JSON encoder and call the encode function and this can throw an error we're going to deal with that later but what we'd like to encode is our message to safe and as you can see this requires an encoding type but since we're using codable we could use both or we could encode and decode our message since we are just going to send information to our API and not retrieve information what we could also have done is just used uncodable right here so this would also have worked just fine so now we have our HTTP body now we have two requests but we still have to work with that request and actually make this request using a data task therefore I'm defining a data task using a URL session shared and then using a data task with our URL request and once this is finished or we get a response we get a data or we get a data check back and we get a response back and also an era object which we are not going to use in that case and now we have to actually ensure that there is an HTTP response we have to check the response status is 200 which would mean it's okay and this is the code returned by our API upon a successful safe so we need also there's the last thing we need to do ensure there's data in our response body so we're going to check that using a simple guard let's statement using HTTP responds and try RS palms try to assign the response casts that to an HTTP URL response then we also need to check if the HTTP response responds and its status code is equal to 200 which would mean ok and then we also need to check if we get JSON theta just assign the data object and if something fails here then we're going to call our completion handler and just tell it that there was a failure and that we had a response problem and here we're actually missing ap so in that case we do have a problem we cannot really continue which means that we also need to return and do not proceed with our function but if we get all of this information that we actually need we can do another do try catch block right here so I'm creating a message message data object here using a try statement to actually catch errors that come from Jason or from the JSON decoder and then decode our message and this only works because we have actually made our message type codable which means again decodable and uncodable and if we only had given it the encode protocol then we could not and if we just adopted the uncodable protocol then we could not have decoded it right now but oops what we'd like to put here is our message type and self from our JSON data which means that we now have message data and we can call our completion Handler and tell it that this was successful and pass along the message data object so this is all we need to do here and now we can start catching our arrows so here again we have a completion but with a failure here we would have a decoding problem so this is the first one now we have our data tasks which not yet resumed so calling the resume function on the data task alright and the last era that we have here is that we are trying our encoding here and this is actually something let's just instead of other problem let's just say encoding problem and then also catch at a catch block right here and call completion failure with an encoding problem all right so this is actually what we have to do to make a post request in that case and the whole magic actually happens here when we set the HTTP method we set the HTTP header field content type to JSON in our case we are working with the JSON encoder here to actually take our message text and encoded as JSON and then send it to our API and then we just react to the different scenarios here and in the best case we get a success message everything works fine and we can actually again display the data that we have received or do something else and this is what we are going to do in our viewcontroller because we still have to call this function so we have a text here which is going to be the message that we'd like to send but we do not have is a message object at this moment so I'm going to initialize a new message object which receives the message as a string so I just pass along the text that I get from a text field in the alert controller and now can just create my post request and initialize it with my API request struct and a endpoint which is messages in my case and now all we have to do is use the post request and hit the save function so here I can pass along the message object that I have just created and for the completion handler I just have to add some curly brace this year and then what we get here is a result object which we can switch through so I'm switching through my result so we have the case success which gives me a message object which should give me a message object which would mean that could just print something like the following message has been sent just pass this through here using string interpolation accessing my message object or the message property of my message we could work on the naming here and the second case is failure which would give me an error object and here I can also print an error occurred and just pass along this object right here and now our result or our switch through the result object is also exhaustive and we can actually run our application in the simulator bring up our website here to access the API and see what we've actually done and here we have the simulator and now let me just quickly press on sent message and now let's say a cool message sent this and as you can see the following message has been send a cool message and in Safari if I reload my page I get a cool message so this was a basic and simple approach to actually sending information to an API using the post request I hope this is helpful to you I thank you so much for watching subscribe to this channel to not miss any new tutorials and I'll see you in the next one
Info
Channel: Brian Advent
Views: 49,225
Rating: undefined out of 5
Keywords: Swift, Xcode (Software), OS X (Operating System), Core Data (Software), IOS (Software), Tutorial, programming, iphone, ipad, Macintosh (Computer), Apple Inc. (Organization), IOS 8, ios9, CloudKit, iOS10, Swift 3, firebase, firestore, ios11, swift 4, ios12, swift 5, API, HTTP
Id: EuNThe245nk
Channel Id: undefined
Length: 18min 20sec (1100 seconds)
Published: Sat May 18 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.