Skip to content
Related Articles

Related Articles

Improve Article

Creating First REST API with FastAPI

  • Last Updated : 05 Sep, 2020

FastAPI :
FastAPI is modern Web Framework . It is used for building API and is very easy to learn .

Features of FastAPI :

  • High Performance than many Web Frameworks, faster than Node.js, etc .
  • Easy to Develop API’s
  • Production Ready
  • Well Documentation to learn code fast
  • Swagger UI to form API Documentation
  • Avoid Redundancy of Code
  • Easy Testing
  • Support for GraphQL, Background Fetching, Dependency Injection

CREATING REST API USING FastAPI :

  • Install Python 3 and pip/pip3 according to your Operating System
  • Now, install fastapi using pip or pip3 :
       pip install fastapi
    
  • Install the uvicorn which is the Asynchronous Gateway Interface for your Server using :



      pip install uvicorn
    
  • Now create a main.py file and import fastapi, also create a server
      from fastapi import FastAPI
      app = FastAPI()
    
  • Now, let’s add the code for sample get request as shown below :
     @app.get("/")
     def read_root():
        return {"Hello": "World"}
    
  • Hence, the main.py file will look like :




    from fastapi import FastAPI
    app = FastAPI()
     
    @app.get("/")
    def first_example():
        """
           GFG Example First Fast API Example 
        """
       return {"GFG Example": "FastAPI"}
  • Now, start the server using
    uvicorn main:app --reload
    
  • Now open the browser and open http://localhost:8000/docs or http://127.0.0.1:8000/docs
    You will be able to see the Swagger UI Home page as below :
    Swagger UI
  • Expand the “First Example” :
    Expanded Swagger UI
  • Now try to Execute the API, you will get the success status with 200 code .
    The Response will be {“GFG Example”: “FastAPI”} as shown below :
    First Example API Execution

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :