Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Python FastAPI crash course: Part 3
Eric The Coder
Eric The Coder

Posted on

     

Python FastAPI crash course: Part 3

Here is a crash course (series of articles) that will allow you to create an API in Python with FastAPI.

To not miss anything follow me on twitter:https://twitter.com/EricTheCoder_


POST

So far we have covered the READ of CRUD, now let's see the "Create".

Here it is no longer a question of reading data but of creating a new one.

To create a new product we need to send some information to the server, and to do this we will need to use the HTTP POST action

POST www.example.com/products
Enter fullscreen modeExit fullscreen mode

The POST action sends data from the client to the server.

Example

We will do an example and add the product "MacBook" to our existing product list.

Here is the expected result:

products=[{"id":1,"name":"iPad","price":599},{"id":2,"name":"iPhone","price":999},{"id":3,"name":"iWatch","price":699},{"id":4,"name":"MacBook","price":1299},]
Enter fullscreen modeExit fullscreen mode

To do a POST with FastAPI here is the code you must use

@app.post("/products")defcreate_product(product:dict,response:Response):product["id"]=len(products)+1products.append(product)response.status_code=201returnproduct
Enter fullscreen modeExit fullscreen mode

Let's take this code line by line:

@app.post("/products")
Enter fullscreen modeExit fullscreen mode

This code is used to specify to FastAPI that this request will be a POST "/products" action

defcreate_product(product:dict,response:Response):
Enter fullscreen modeExit fullscreen mode

This code is used to define the function that will be launched when the server receives the "POST/products" request.

The function contains two parameters, one for the product and the other for a reference to the response object.

Note that when performing a POST action, the data to be sent must be included in the body of the request and must be in JSON text format.

In this example we see all the power and ease of FastAPI. FastAPI knows it is a POST request, so it will automatically take the JSON that is in the request body, convert it to a Python dictionary and place the result in the first parameter (product).

So we can then use this "product" parameter to add the product to our product list.

product["id"]=len(products)+1products.append(product)
Enter fullscreen modeExit fullscreen mode

Once the product has been added successfully, the appropriate status code should be returned.

response.status_code=201
Enter fullscreen modeExit fullscreen mode

This code is used to return the status code 201 (Created). Which indicates that the product is indeed created successfully.

Finally, by convention, the new product is always returned with the response.

returnproduct
Enter fullscreen modeExit fullscreen mode

Testing an HTTP Post action

Web browsers do not allow you to initiate a POST request. So it will not be possible to test this new API from the browser.

There are several other ways to do this. We could use software like Postman and test our requests from Postman.

One of the advantages of FastAPI is that it automatically generates documentation for our API. This documentation allows users to understand how to use our API, what are the available URL paths and also to execute requests.

We will therefore be able to use the documentation to test our API

As mentioned, in the case of our API the documentation is created automatically. To view it, start the server

$uvicornfirst-api:app--reload
Enter fullscreen modeExit fullscreen mode

and visit /docs

http://127.0.0.1:8000/docs
Enter fullscreen modeExit fullscreen mode

The documentation will be displayed on the screen!
Image description

To test a URL path it's very simple, just click on the path name and FastAPI will reveal an interface allowing you to test this endpoint.

For example if you click on POST /products you will see appear

Image description

You can then click on "Try it out", enter the data to add in the "Request body" section (see example below)

Image description

The data is in JSON text format

{"name":"MacBook","price":1299}
Enter fullscreen modeExit fullscreen mode

Finally click "Execute", the doc send the POST request to your FastAPI server

The response status code as well as the response itself will also be displayed on the page.

Image description

This automatic documentation is yet another great demonstration of the power and ease of FastAPI.

If you wish, you can click on all the endpoints one after the other in order to test them.

Validation

Let's go back to the last example we created

@app.post("/products")defcreate_product(product:dict,response:Response):product["id"]=len(products)+1products.append(product)response.status_code=201returnproduct
Enter fullscreen modeExit fullscreen mode

The @app.post() function works but has several shortcomings. In fact, there is no validation and no error message is returned if this validation does not pass.

For example, to create a new product we need the "name" and "price". What happens if only the "name" is sent but not the "price"?

Or what if the "price" is not a number format.

I could give you several more examples but I think you understand the concept.

To make these validations and return the associated error messages, we would have to add a lot of code to our function. And this code would have to be repeated for each action and each resource. All of this would greatly complicate our application.

Fortunately, FastAPI is named "Fast" API. So there is a very simple way to implement an automatic validation system. This system is the schema!

The schema

Schemas are data models that FastAPI uses to validate our functions.

For example we could define a schema like this:

frompydanticimportBaseModelclassProduct(BaseModel):name:strprice:float
Enter fullscreen modeExit fullscreen mode

This data model is very easy to understand. We have a "Product" entity which contains the "name" and "price" attributes. We can even define what the type attributes are.

Once we have defined our data model, we can modify our @app.post() function

@app.post("/products")defcreate_product(new_product:Product,response:Response):product=new_product.dict()product["id"]=len(products)+1products.append(product)response.status_code=201returnproduct
Enter fullscreen modeExit fullscreen mode

We replaced the "dict" type parameter with a "Product" type parameter.

Once this change is made, if you test this function, you will see that FastAPI now applies automatic validation and will return an error if what you send does not respect the "Product" model.

PUT

The PUT action is used to modify an existing resource. Like the POST action, the data to be modified must be sent with the request.

Here is an example of a PUT function

@app.put("/products/{id}")defedit_product(id:int,edited_product:Product,response:Response):forproductinproducts:ifproduct["id"]==id:product['name']=edited_product.nameproduct['price']=edited_product.priceresponse.status_code=200returnproductelse:response.status_code=404return"Product Not found"
Enter fullscreen modeExit fullscreen mode

There is nothing really new here. These are exactly the same concepts that we discovered a little earlier.

DELETTE

The DELETE action allows you to delete a resource. Here is the code to implement this action

@app.delete("/products/{id}")defdestroy_product(id:int,response:Response):forproductinproducts:ifproduct["id"]==id:products.remove(product)response.status_code=204return"Product Deleted"else:response.status_code=404return"Product Not found"
Enter fullscreen modeExit fullscreen mode

Database

The code you have just created to implement CRUD is fine, but it still lacks an important notion and that is to link the resource with a database. The next section will explain how to do it step by step.

Conclusion

That's all for today, follow me on twitter:https://twitter.com/EricTheCoder_ to be notified of the publication of the next article.

Top comments(6)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
andrewbaisden profile image
Andrew Baisden
Software Developer | Content Creator | AI, Tech, Programming
  • Location
    London, UK
  • Education
    Bachelor Degree Computer Science
  • Work
    Software Developer
  • Joined

FastAPI is so nice to use.

CollapseExpand
 
sush_5191 profile image
Sushant Garudkar
Full Stack (Web2/Web3) Developer | Business | Spirituality - Pune, MH, India

Nice do you know where to head next after this quick intro or have you found any valuable resource to learn more about it! kindly tell me if any 'cause I've just found this valuable guide!

CollapseExpand
 
andrewbaisden profile image
Andrew Baisden
Software Developer | Content Creator | AI, Tech, Programming
  • Location
    London, UK
  • Education
    Bachelor Degree Computer Science
  • Work
    Software Developer
  • Joined

The official documentation should be good enough. One of my colleagues is using FastAPI in a project thats why I thought it was cool.

Thread Thread
 
timsmall profile image
Samuel Ogunleye
a young guy who's vision is to affect the community positively.
  • Education
    Ekiti state university
  • Work
    CEO at the Visiblility tech
  • Joined

Hello. Can you share what the fastApi your colleagues and let see where I can help out

Thread Thread
 
andrewbaisden profile image
Andrew Baisden
Software Developer | Content Creator | AI, Tech, Programming
  • Location
    London, UK
  • Education
    Bachelor Degree Computer Science
  • Work
    Software Developer
  • Joined

It was in an old project so its not relevant anymore.

CollapseExpand
 
sush_5191 profile image
Sushant Garudkar
Full Stack (Web2/Web3) Developer | Business | Spirituality - Pune, MH, India

Nice what's next and when it will be updated ❤️!

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Businessman and blogger #Javascript, #Python and #PHP. My favorite frameworks/librairies are #React, #Laravel, and #Django. I am also a fan of #TailwindCSS
  • Location
    Canada
  • Joined

More fromEric The Coder

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp