Store API – Creating REST API in Laravel(Part IV)

Store Api is an api end point for storing data to database. We are using article as our entity so it will be article store api. In previous article, we have added request validation. We have already created database structure, eloquent model, routes, controller functions. Now, we will add all necessary logic to store function in controller to create store api.

We have already added store api route in api.php file, you can see this post for reference.

Let’s add the logic in the store function of ArticleController like this:


At first, we have imported the Article model. Then, we will extend our controller from ApiController so that we can send response based on processing of request. Finally, we have added logic to store article in the store function.

We have added try catch block to make sure storing of article. For successful storage of the article, we will return success with HTTP_OK status. In case of failure, we will return failed response with error message.


Test using Postman(store api)

I’m using ubantu local server. I’ve hosted my application at localhost:8000. Now, open postman then follow the following steps:

1.Select method type to POST

2. Set route to http://localhost:8000/api/articles

3. Add json data in body section of request.

Example:

4. Send the request you will get output like this

Screenshot

Store API Testing

You can find all the details in github: https://github.com/sagautam5/laravel-rest-api

In the next article, we will discuss about update api for the article.


sagautam5

sagautam5

Computer Enginner, A Laravel Developer,
http://sagargautam.stacklearning.com

Leave a Reply

Your email address will not be published. Required fields are marked *